behive 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. {behive-0.2.0/src/behive.egg-info → behive-0.2.2}/PKG-INFO +1 -1
  2. {behive-0.2.0 → behive-0.2.2}/pyproject.toml +1 -1
  3. {behive-0.2.0 → behive-0.2.2}/src/behive/__init__.py +1 -1
  4. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/__init__.py +3 -0
  5. behive-0.2.2/src/behive/engine/__main__.py +29 -0
  6. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/bionic_quorum.py +10 -5
  7. behive-0.2.2/src/behive/engine/constants.py +58 -0
  8. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/db.py +23 -12
  9. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/domain_reputation.py +16 -13
  10. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/drones.py +41 -31
  11. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/events.py +9 -4
  12. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/guardrail.py +29 -20
  13. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/harvest.py +60 -49
  14. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/orchestrator.py +200 -192
  15. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/preprocessor.py +10 -4
  16. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/prescout.py +82 -68
  17. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/process.py +79 -59
  18. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/quality.py +8 -4
  19. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/queen_calibrator.py +25 -22
  20. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/queen_fact_mem.py +25 -22
  21. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/queen_memory.py +6 -1
  22. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/queen_primer.py +8 -6
  23. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/scout.py +49 -43
  24. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/synth.py +149 -145
  25. {behive-0.2.0 → behive-0.2.2/src/behive.egg-info}/PKG-INFO +1 -1
  26. {behive-0.2.0 → behive-0.2.2}/src/behive.egg-info/SOURCES.txt +1 -0
  27. {behive-0.2.0 → behive-0.2.2}/tests/test_smoke.py +2 -2
  28. behive-0.2.0/src/behive/engine/__main__.py +0 -16
  29. {behive-0.2.0 → behive-0.2.2}/LICENSE +0 -0
  30. {behive-0.2.0 → behive-0.2.2}/README.md +0 -0
  31. {behive-0.2.0 → behive-0.2.2}/setup.cfg +0 -0
  32. {behive-0.2.0 → behive-0.2.2}/src/behive/cli.py +0 -0
  33. {behive-0.2.0 → behive-0.2.2}/src/behive/client.py +0 -0
  34. {behive-0.2.0 → behive-0.2.2}/src/behive/compat/__init__.py +0 -0
  35. {behive-0.2.0 → behive-0.2.2}/src/behive/compat/shims.py +0 -0
  36. {behive-0.2.0 → behive-0.2.2}/src/behive/config.py +0 -0
  37. {behive-0.2.0 → behive-0.2.2}/src/behive/engine/api_scout.py +0 -0
  38. {behive-0.2.0 → behive-0.2.2}/src/behive/mcp_server.py +0 -0
  39. {behive-0.2.0 → behive-0.2.2}/src/behive/models.py +0 -0
  40. {behive-0.2.0 → behive-0.2.2}/src/behive/server.py +0 -0
  41. {behive-0.2.0 → behive-0.2.2}/src/behive.egg-info/dependency_links.txt +0 -0
  42. {behive-0.2.0 → behive-0.2.2}/src/behive.egg-info/entry_points.txt +0 -0
  43. {behive-0.2.0 → behive-0.2.2}/src/behive.egg-info/requires.txt +0 -0
  44. {behive-0.2.0 → behive-0.2.2}/src/behive.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: behive
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Research engine that builds structured knowledge graphs from any topic
5
5
  Author-email: QA10 <hello@qa10.io>
6
6
  License-Expression: MIT
@@ -7,7 +7,7 @@ where = ["src"]
7
7
 
8
8
  [project]
9
9
  name = "behive"
10
- version = "0.2.0"
10
+ version = "0.2.2"
11
11
  description = "Research engine that builds structured knowledge graphs from any topic"
12
12
  readme = "README.md"
13
13
  license = "MIT"
@@ -10,7 +10,7 @@ Usage:
10
10
  print(result.report) # Synthesized markdown report
11
11
  """
12
12
 
13
- __version__ = "0.2.0"
13
+ __version__ = "0.2.2"
14
14
 
15
15
  from behive.client import research, BeHiveClient
16
16
  from behive.models import ResearchResult, Claim, Entity
@@ -34,7 +34,10 @@ Usage:
34
34
  from behive.engine.db import get_pg_connection
35
35
  from behive.engine.orchestrator import run_mission
36
36
  """
37
+ import logging
37
38
 
39
+
40
+ log = logging.getLogger(__name__)
38
41
  __all__ = [
39
42
  "orchestrator",
40
43
  "scout",
@@ -0,0 +1,29 @@
1
+ """Allow running: python -m behive.engine 'topic'"""
2
+ import sys
3
+ import os
4
+ import logging
5
+
6
+ log = logging.getLogger(__name__)
7
+
8
+ # Install compat shims
9
+ try:
10
+ from behive.compat.shims import install_shims, install_ops_shim
11
+ install_shims()
12
+ install_ops_shim()
13
+ except ImportError:
14
+ pass
15
+
16
+ from behive.engine.orchestrator import cmd_run
17
+
18
+
19
+ def main() -> None:
20
+ """CLI entry point for running research from the command line."""
21
+ if len(sys.argv) < 2:
22
+ print("Usage: python -m behive.engine 'research topic'")
23
+ sys.exit(1)
24
+ topic = ' '.join(sys.argv[1:])
25
+ cmd_run(topic)
26
+
27
+
28
+ if __name__ == "__main__":
29
+ main()
@@ -57,7 +57,7 @@ DB_PATH = os.environ.get("BEHIVE_LEGACY_DB", "") # Legacy — PostgreSQL is pri
57
57
  # THRESHOLDS
58
58
  # ─────────────────────────────────────────────────────────────────────────────
59
59
  QUORUM_MIN = 25 # min harvestable sources → pszczoły lecą
60
- QUORUM_SOFT = 40 # soft target — poniżej uruchamia expansion ale nie blokuje
60
+ QUORUM_SOFT = 40 # soft target — poniżej uruchamia expansion ale not blokuje
61
61
  QUORUM_HARD_MIN = 15 # absolutne minimum — poniżej ZAWSZE expansion
62
62
  MAX_EXPANSIONS = 2 # maks ile razy rozszerzamy zasięg
63
63
  EXPANSION_QUERIES = 5 # ile dodatkowych queries per expansion
@@ -65,6 +65,7 @@ EXPANSION_QUERIES = 5 # ile dodatkowych queries per expansion
65
65
 
66
66
  @dataclass
67
67
  class QuorumResult:
68
+ """Bionic quorum voting result with confidence and expansion queries."""
68
69
  mission_id: str
69
70
  harvestable_count: int
70
71
  total_sources: int
@@ -76,6 +77,7 @@ class QuorumResult:
76
77
  report: str = ""
77
78
 
78
79
  def summary(self) -> str:
80
+ """Return human-readable summary of the quorum result."""
79
81
  status = "✅ QUORUM MET" if self.quorum_met else "⚠️ QUORUM FAILED"
80
82
  exp = f" → expansion round {self.expansion_round + 1}" if self.needs_expansion else ""
81
83
  return (
@@ -117,7 +119,8 @@ class QuorumChecker:
117
119
  ).fetchone()
118
120
  con.close()
119
121
  return row[0] if row else ""
120
- except Exception:
122
+ except Exception as e:
123
+ log.debug(f"Suppressed in bionic_quorum.py: {e}")
121
124
  return ""
122
125
 
123
126
  def _load_expansion_count(self) -> int:
@@ -130,7 +133,8 @@ class QuorumChecker:
130
133
  """, [self.mission_id]).fetchone()
131
134
  con.close()
132
135
  return row[0] if row else 0
133
- except Exception:
136
+ except Exception as e:
137
+ log.debug(f"Suppressed in bionic_quorum.py: {e}")
134
138
  return 0
135
139
 
136
140
  def check(self) -> QuorumResult:
@@ -150,14 +154,15 @@ class QuorumChecker:
150
154
  AND score_total >= 10
151
155
  """, [self.mission_id]).fetchone()[0]
152
156
 
153
- # Prescout skip count (jeśli prescout już ran)
157
+ # Prescout skip count (if prescout already ran)
154
158
  try:
155
159
  skip_count = con.execute("""
156
160
  SELECT COUNT(*) FROM hive_prescout_map
157
161
  WHERE mission_id = ?
158
162
  AND routing_decision = 'skip'
159
163
  """, [self.mission_id]).fetchone()[0]
160
- except Exception:
164
+ except Exception as e:
165
+ log.debug(f"Suppressed in bionic_quorum.py: {e}")
161
166
  skip_count = 0
162
167
 
163
168
  con.close()
@@ -0,0 +1,58 @@
1
+ """
2
+ Shared constants for the BeHive engine.
3
+
4
+ Centralizes magic strings and config values used across multiple modules.
5
+ """
6
+
7
+ # ═══════════════════════════════════════════════════════════════════════════════
8
+ # Pipeline stages (used in config, logging, events)
9
+ # ═══════════════════════════════════════════════════════════════════════════════
10
+ STAGE_SCOUT = "scout"
11
+ STAGE_HARVEST = "harvest"
12
+ STAGE_PROCESS = "process"
13
+ STAGE_SYNTH = "synth"
14
+ ALL_STAGES = (STAGE_SCOUT, STAGE_HARVEST, STAGE_PROCESS, STAGE_SYNTH)
15
+
16
+ # ═══════════════════════════════════════════════════════════════════════════════
17
+ # AWS / Bedrock constants
18
+ # ═══════════════════════════════════════════════════════════════════════════════
19
+ BEDROCK_SERVICE = "bedrock-runtime"
20
+ BEDROCK_API_VERSION = "bedrock-2023-05-31"
21
+ BEDROCK_ANTHROPIC_VERSION = "bedrock-2023-05-31"
22
+
23
+ # ═══════════════════════════════════════════════════════════════════════════════
24
+ # DB sequences and table names
25
+ # ═══════════════════════════════════════════════════════════════════════════════
26
+ SEQ_FACTS = "hive_facts_seq"
27
+ TABLE_MISSIONS = "hive_missions"
28
+ TABLE_SOURCES = "hive_sources"
29
+ TABLE_CONTENT = "hive_content"
30
+ TABLE_CLAIMS = "hive_claims"
31
+ TABLE_ENTITIES = "hive_entities"
32
+ TABLE_FACTS = "hive_facts"
33
+ TABLE_EVENTS = "hive_events"
34
+ TABLE_CLUSTERS = "hive_clusters"
35
+
36
+ # ═══════════════════════════════════════════════════════════════════════════════
37
+ # Scout source types
38
+ # ═══════════════════════════════════════════════════════════════════════════════
39
+ SOURCE_GOOGLE_RSS = "google_rss"
40
+ SOURCE_DDG_FILETYPE = "ddg_filetype"
41
+ SOURCE_API = "api"
42
+ SOURCE_DIRECT = "direct"
43
+
44
+ # ═══════════════════════════════════════════════════════════════════════════════
45
+ # Process / Quality thresholds
46
+ # ═══════════════════════════════════════════════════════════════════════════════
47
+ DEFAULT_QUALITY_THRESHOLD = 0.45
48
+ DEFAULT_CONFIDENCE_THRESHOLD = 0.30
49
+ MAX_TOKENS_HAIKU = 4096
50
+ MAX_TOKENS_SONNET = 8192
51
+
52
+ # ═══════════════════════════════════════════════════════════════════════════════
53
+ # Queen internal keys
54
+ # ═══════════════════════════════════════════════════════════════════════════════
55
+ KEY_MEMORY_BLOCK = "memory_block"
56
+ KEY_SUBJECT_PROFILE = "subject_profile"
57
+ KEY_QUALITY_SCORE = "quality_score"
58
+ KEY_MAX_TOKENS = "max_tokens"
@@ -18,7 +18,10 @@ Features vs DuckDB:
18
18
  import os
19
19
  import psycopg2
20
20
  import psycopg2.extras
21
+ import logging
21
22
 
23
+
24
+ log = logging.getLogger(__name__)
22
25
  # Module-level constants for compat with legacy hive2_db imports
23
26
  DB_BACKEND = "postgres"
24
27
  DB_PATH = os.environ.get("BEHIVE_DB_URL", "postgresql://localhost:***@localhost:5432/behive")
@@ -68,7 +71,7 @@ def get_pg_connection() -> psycopg2.extensions.connection:
68
71
 
69
72
 
70
73
  @contextmanager
71
- def pg_connection():
74
+ def pg_connection() -> object:
72
75
  """Context manager for pooled connections. Auto-returns to pool."""
73
76
  pool = get_pg_pool()
74
77
  conn = pool.getconn()
@@ -83,7 +86,7 @@ def pg_connection():
83
86
 
84
87
 
85
88
  @contextmanager
86
- def pg_cursor(commit: bool = True):
89
+ def pg_cursor(commit: bool = True) -> object:
87
90
  """Context manager for a cursor with auto-commit/rollback."""
88
91
  with pg_connection() as conn:
89
92
  cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
@@ -134,11 +137,13 @@ class PgConnection:
134
137
  if not self._read_only:
135
138
  self._conn.commit()
136
139
  except Exception as e:
140
+ log.debug(f"Exception in db.py: {e}")
137
141
  self._conn.rollback()
138
142
  raise
139
143
  return self
140
144
 
141
- def fetchone(self):
145
+ def fetchone(self) -> tuple | None:
146
+ """Execute query and return first row or None."""
142
147
  if self._cursor:
143
148
  return self._cursor.fetchone()
144
149
  return None
@@ -161,16 +166,18 @@ class PgConnection:
161
166
  if not self._read_only:
162
167
  self._conn.commit()
163
168
  except Exception as e:
169
+ log.debug(f"Exception in db.py: {e}")
164
170
  self._conn.rollback()
165
171
  raise
166
172
  return self
167
173
 
168
- def fetchall(self):
174
+ def fetchall(self) -> list:
175
+ """Execute query and return all rows."""
169
176
  if self._cursor:
170
177
  return self._cursor.fetchall()
171
178
  return []
172
179
 
173
- def fetchdf(self):
180
+ def fetchdf(self) -> object:
174
181
  """DuckDB .fetchdf() compatibility → returns pandas DataFrame."""
175
182
  import pandas as pd
176
183
  if self._cursor:
@@ -180,19 +187,22 @@ class PgConnection:
180
187
  return pd.DataFrame()
181
188
 
182
189
  @property
183
- def description(self):
190
+ def description(self) -> list | None:
184
191
  """Cursor description (column names + types)."""
185
192
  if self._cursor:
186
193
  return self._cursor.description
187
194
  return None
188
195
 
189
- def commit(self):
196
+ def commit(self) -> None:
197
+ """Commit the current transaction."""
190
198
  self._conn.commit()
191
199
 
192
- def rollback(self):
200
+ def rollback(self) -> None:
201
+ """Rollback the current transaction."""
193
202
  self._conn.rollback()
194
203
 
195
- def close(self):
204
+ def close(self) -> None:
205
+ """Close the database connection."""
196
206
  if self._cursor:
197
207
  self._cursor.close()
198
208
  self._cursor = None
@@ -200,7 +210,7 @@ class PgConnection:
200
210
  self._pool.putconn(self._conn)
201
211
  self._conn = None
202
212
 
203
- def cursor(self):
213
+ def cursor(self) -> object:
204
214
  """Return a new cursor (DuckDB .cursor() compat)."""
205
215
  return self._conn.cursor()
206
216
 
@@ -243,7 +253,7 @@ def connect(database: str = None, read_only: bool = False) -> PgConnection:
243
253
 
244
254
  # ─── Utility Functions ─────────────────────────────────────────────────────
245
255
 
246
- def insert_batch(table: str, rows: list[dict], on_conflict: str = "DO NOTHING"):
256
+ def insert_batch(table: str, rows: list[dict], on_conflict: str = "DO NOTHING") -> None:
247
257
  """Batch insert with ON CONFLICT handling."""
248
258
  if not rows:
249
259
  return 0
@@ -265,7 +275,7 @@ def insert_batch(table: str, rows: list[dict], on_conflict: str = "DO NOTHING"):
265
275
  return len(values)
266
276
 
267
277
 
268
- def upsert_batch(table: str, rows: list[dict], conflict_cols: list[str], update_cols: list[str] = None):
278
+ def upsert_batch(table: str, rows: list[dict], conflict_cols: list[str], update_cols: list[str] = None) -> None:
269
279
  """Batch upsert (INSERT ... ON CONFLICT ... DO UPDATE)."""
270
280
  if not rows:
271
281
  return 0
@@ -313,6 +323,7 @@ def health_check() -> dict:
313
323
  "top_tables": [dict(t) for t in tables],
314
324
  }
315
325
  except Exception as e:
326
+ log.debug(f"Exception in db.py: {e}")
316
327
  return {"status": "error", "error": str(e)}
317
328
 
318
329
 
@@ -9,7 +9,7 @@ Ten moduł robi to samo dla domen: akumuluje wiedzę negatywną cross-mission
9
9
  i eliminuje "zarażone" źródła z kolejnych harvests.
10
10
 
11
11
  Schemat:
12
- hive_domain_reputation (DuckDB persistent)
12
+ hive_domain_reputation (persistent)
13
13
  domain VARCHAR PK
14
14
  avg_quality FLOAT — średnia jakość treści (0.0–1.0)
15
15
  harvest_count INT — ile razy harvestowane
@@ -25,8 +25,8 @@ Public API:
25
25
  rep = DomainReputation()
26
26
 
27
27
  # Przed harvest
28
- factor = rep.get_score_boost(url) # 0.5–1.5 (mnożnik dla score_total)
29
- skip = rep.should_skip(url) # True jeśli blacklisted
28
+ factor = rep.get_score_boost(url) # 0.5–1.5 (multiplier for score_total)
29
+ skip = rep.should_skip(url) # True if blacklisted
30
30
 
31
31
  # Po harvest (aktualizacja)
32
32
  rep.update(url, quality_score, success)
@@ -75,7 +75,7 @@ _BAD_QUALITY_THRESHOLD = 0.3 # pojedynczy harvest < X = "zły"
75
75
  _BOOST_HIGH = 1.35 # boost dla zaufanych domen (avg > 0.75)
76
76
  _BOOST_MED = 1.10 # lekki boost (avg 0.55–0.75)
77
77
  _BOOST_LOW = 0.65 # kara (avg 0.25–0.45)
78
- _BOOST_VERY_LOW = 0.35 # duża kara (avg < 0.25, nie blacklisted yet)
78
+ _BOOST_VERY_LOW = 0.35 # duża kara (avg < 0.25, not blacklisted yet)
79
79
 
80
80
 
81
81
  def _extract_domain(url: str) -> str:
@@ -88,7 +88,8 @@ def _extract_domain(url: str) -> str:
88
88
  # strip port
89
89
  domain = domain.split(":")[0]
90
90
  return domain
91
- except Exception:
91
+ except Exception as e:
92
+ log.debug(f"Suppressed in domain_reputation.py: {e}")
92
93
  return url[:100]
93
94
 
94
95
 
@@ -176,7 +177,7 @@ class DomainReputation:
176
177
  if rec["blacklisted"]:
177
178
  return 0.0 # wyklucz całkowicie
178
179
 
179
- # Potrzebujemy min. 2 harvests żeby mieć sens
180
+ # Need min 2 harvests to be meaningful
180
181
  if rec["harvest_count"] < 2:
181
182
  return 1.0
182
183
 
@@ -211,7 +212,7 @@ class DomainReputation:
211
212
  # PUBLIC WRITE API
212
213
  # ─────────────────────────────────────────────────────────────────────
213
214
 
214
- def update(self, url: str, quality_score: float, success: bool = True):
215
+ def update(self, url: str, quality_score: float, success: bool = True) -> None:
215
216
  """
216
217
  Rejestruje wynik harvestu dla domeny.
217
218
  Wywoływać po każdym _harvest_one() w HarvesterBee.
@@ -227,7 +228,7 @@ class DomainReputation:
227
228
  p["successes"].append(success)
228
229
  p["consecutive_bad"] = p["consecutive_bad"] + 1 if is_bad else 0
229
230
  else:
230
- # Ładuj istniejące lub inicjuj nowe
231
+ # Load existing or initialize new
231
232
  rec = self._load(domain)
232
233
  base_count = rec["harvest_count"] if rec else 0
233
234
  base_quality = rec["avg_quality"] if rec else 0.5
@@ -249,9 +250,9 @@ class DomainReputation:
249
250
  self._cache[domain]["consecutive_bad"] + 1 if is_bad else 0
250
251
  )
251
252
 
252
- def flush(self):
253
+ def flush(self) -> None:
253
254
  """
254
- Commituje wszystkie pending updates do DuckDB.
255
+ Commits all pending updates to database.
255
256
  Wywołaj po zakończeniu harvest misji.
256
257
  """
257
258
  if not self._pending_updates:
@@ -268,7 +269,7 @@ class DomainReputation:
268
269
  int(p["base_count"] * 0.7) + new_successes # aprox prior successes
269
270
  )
270
271
 
271
- # Nowa średnia jakości (exponential moving average — faworyzuje nowe dane)
272
+ # New quality average (EMA — favors recent data)
272
273
  if p["base_count"] > 0:
273
274
  alpha = min(0.4, new_harvests / (p["base_count"] + new_harvests))
274
275
  new_avg = (1 - alpha) * p["base_quality"] + alpha * (
@@ -390,6 +391,7 @@ class DomainReputation:
390
391
  lines.append(f" {d:<45} avg={q:.2f} harvests={h} boost={boost}x {reason[:40]}")
391
392
  return "\n".join(lines)
392
393
  except Exception as e:
394
+ log.debug(f"Exception in domain_reputation.py: {e}")
393
395
  return f"Domain reputation report error: {e}"
394
396
 
395
397
 
@@ -400,6 +402,7 @@ _global_rep: Optional[DomainReputation] = None
400
402
 
401
403
 
402
404
  def get_reputation() -> DomainReputation:
405
+ """Get domain reputation score and history."""
403
406
  global _global_rep
404
407
  if _global_rep is None:
405
408
  _global_rep = DomainReputation()
@@ -435,7 +438,7 @@ if __name__ == "__main__":
435
438
  print(f" {url[:50]:50s} skip={skip} boost={boost:.2f}x")
436
439
  print(rep.report())
437
440
  elif "--blacklist" in sys.argv:
438
- # ręczne blacklistowanie
441
+ # manual blacklisting
439
442
  try:
440
443
  idx = sys.argv.index("--blacklist")
441
444
  domain = sys.argv[idx + 1]
@@ -451,7 +454,7 @@ if __name__ == "__main__":
451
454
  updated_at=excluded.updated_at
452
455
  """, [domain, reason])
453
456
  con.close()
454
- print(f"✓ Blacklisted: {domain} ({reason})")
457
+ log.info(f"✓ Blacklisted: {domain} ({reason})")
455
458
  except (IndexError, Exception) as e:
456
459
  print(f"Usage: python3 hive2_domain_reputation.py --blacklist domain.com [reason]")
457
460
  print(f"Error: {e}")