behive 0.2.0__tar.gz → 0.2.1__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.
- {behive-0.2.0/src/behive.egg-info → behive-0.2.1}/PKG-INFO +1 -1
- {behive-0.2.0 → behive-0.2.1}/pyproject.toml +1 -1
- {behive-0.2.0 → behive-0.2.1}/src/behive/__init__.py +1 -1
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/__init__.py +3 -0
- behive-0.2.1/src/behive/engine/__main__.py +29 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/bionic_quorum.py +2 -2
- behive-0.2.1/src/behive/engine/constants.py +58 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/db.py +6 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/domain_reputation.py +11 -10
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/drones.py +30 -27
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/events.py +4 -2
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/guardrail.py +22 -19
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/harvest.py +47 -42
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/orchestrator.py +190 -185
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/preprocessor.py +7 -4
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/prescout.py +68 -62
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/process.py +49 -48
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/quality.py +6 -4
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/queen_calibrator.py +20 -20
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/queen_fact_mem.py +22 -22
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/queen_memory.py +4 -1
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/queen_primer.py +6 -5
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/scout.py +43 -41
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/synth.py +108 -123
- {behive-0.2.0 → behive-0.2.1/src/behive.egg-info}/PKG-INFO +1 -1
- {behive-0.2.0 → behive-0.2.1}/src/behive.egg-info/SOURCES.txt +1 -0
- behive-0.2.0/src/behive/engine/__main__.py +0 -16
- {behive-0.2.0 → behive-0.2.1}/LICENSE +0 -0
- {behive-0.2.0 → behive-0.2.1}/README.md +0 -0
- {behive-0.2.0 → behive-0.2.1}/setup.cfg +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/cli.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/client.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/compat/__init__.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/compat/shims.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/config.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/engine/api_scout.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/mcp_server.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/models.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive/server.py +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive.egg-info/dependency_links.txt +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive.egg-info/entry_points.txt +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive.egg-info/requires.txt +0 -0
- {behive-0.2.0 → behive-0.2.1}/src/behive.egg-info/top_level.txt +0 -0
- {behive-0.2.0 → behive-0.2.1}/tests/test_smoke.py +0 -0
|
@@ -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():
|
|
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
|
|
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
|
|
@@ -150,7 +150,7 @@ class QuorumChecker:
|
|
|
150
150
|
AND score_total >= 10
|
|
151
151
|
""", [self.mission_id]).fetchone()[0]
|
|
152
152
|
|
|
153
|
-
# Prescout skip count (
|
|
153
|
+
# Prescout skip count (if prescout already ran)
|
|
154
154
|
try:
|
|
155
155
|
skip_count = con.execute("""
|
|
156
156
|
SELECT COUNT(*) FROM hive_prescout_map
|
|
@@ -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")
|
|
@@ -134,6 +137,7 @@ 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
|
|
@@ -161,6 +165,7 @@ class PgConnection:
|
|
|
161
165
|
if not self._read_only:
|
|
162
166
|
self._conn.commit()
|
|
163
167
|
except Exception as e:
|
|
168
|
+
log.debug(f"Exception in db.py: {e}")
|
|
164
169
|
self._conn.rollback()
|
|
165
170
|
raise
|
|
166
171
|
return self
|
|
@@ -313,6 +318,7 @@ def health_check() -> dict:
|
|
|
313
318
|
"top_tables": [dict(t) for t in tables],
|
|
314
319
|
}
|
|
315
320
|
except Exception as e:
|
|
321
|
+
log.debug(f"Exception in db.py: {e}")
|
|
316
322
|
return {"status": "error", "error": str(e)}
|
|
317
323
|
|
|
318
324
|
|
|
@@ -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 (
|
|
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 (
|
|
29
|
-
skip = rep.should_skip(url) # True
|
|
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,
|
|
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:
|
|
@@ -176,7 +176,7 @@ class DomainReputation:
|
|
|
176
176
|
if rec["blacklisted"]:
|
|
177
177
|
return 0.0 # wyklucz całkowicie
|
|
178
178
|
|
|
179
|
-
#
|
|
179
|
+
# Need min 2 harvests to be meaningful
|
|
180
180
|
if rec["harvest_count"] < 2:
|
|
181
181
|
return 1.0
|
|
182
182
|
|
|
@@ -227,7 +227,7 @@ class DomainReputation:
|
|
|
227
227
|
p["successes"].append(success)
|
|
228
228
|
p["consecutive_bad"] = p["consecutive_bad"] + 1 if is_bad else 0
|
|
229
229
|
else:
|
|
230
|
-
#
|
|
230
|
+
# Load existing or initialize new
|
|
231
231
|
rec = self._load(domain)
|
|
232
232
|
base_count = rec["harvest_count"] if rec else 0
|
|
233
233
|
base_quality = rec["avg_quality"] if rec else 0.5
|
|
@@ -251,7 +251,7 @@ class DomainReputation:
|
|
|
251
251
|
|
|
252
252
|
def flush(self):
|
|
253
253
|
"""
|
|
254
|
-
|
|
254
|
+
Commits all pending updates to database.
|
|
255
255
|
Wywołaj po zakończeniu harvest misji.
|
|
256
256
|
"""
|
|
257
257
|
if not self._pending_updates:
|
|
@@ -268,7 +268,7 @@ class DomainReputation:
|
|
|
268
268
|
int(p["base_count"] * 0.7) + new_successes # aprox prior successes
|
|
269
269
|
)
|
|
270
270
|
|
|
271
|
-
#
|
|
271
|
+
# New quality average (EMA — favors recent data)
|
|
272
272
|
if p["base_count"] > 0:
|
|
273
273
|
alpha = min(0.4, new_harvests / (p["base_count"] + new_harvests))
|
|
274
274
|
new_avg = (1 - alpha) * p["base_quality"] + alpha * (
|
|
@@ -390,6 +390,7 @@ class DomainReputation:
|
|
|
390
390
|
lines.append(f" {d:<45} avg={q:.2f} harvests={h} boost={boost}x {reason[:40]}")
|
|
391
391
|
return "\n".join(lines)
|
|
392
392
|
except Exception as e:
|
|
393
|
+
log.debug(f"Exception in domain_reputation.py: {e}")
|
|
393
394
|
return f"Domain reputation report error: {e}"
|
|
394
395
|
|
|
395
396
|
|
|
@@ -435,7 +436,7 @@ if __name__ == "__main__":
|
|
|
435
436
|
print(f" {url[:50]:50s} skip={skip} boost={boost:.2f}x")
|
|
436
437
|
print(rep.report())
|
|
437
438
|
elif "--blacklist" in sys.argv:
|
|
438
|
-
#
|
|
439
|
+
# manual blacklisting
|
|
439
440
|
try:
|
|
440
441
|
idx = sys.argv.index("--blacklist")
|
|
441
442
|
domain = sys.argv[idx + 1]
|
|
@@ -451,7 +452,7 @@ if __name__ == "__main__":
|
|
|
451
452
|
updated_at=excluded.updated_at
|
|
452
453
|
""", [domain, reason])
|
|
453
454
|
con.close()
|
|
454
|
-
|
|
455
|
+
log.info(f"✓ Blacklisted: {domain} ({reason})")
|
|
455
456
|
except (IndexError, Exception) as e:
|
|
456
457
|
print(f"Usage: python3 hive2_domain_reputation.py --blacklist domain.com [reason]")
|
|
457
458
|
print(f"Error: {e}")
|
|
@@ -63,7 +63,7 @@ DB_PATH = "" # Legacy — PostgreSQL is primary
|
|
|
63
63
|
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
64
64
|
|
|
65
65
|
UA_POOL = [
|
|
66
|
-
# Chrome 131 Windows (
|
|
66
|
+
# Chrome 131 Windows (default — highest trust)
|
|
67
67
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
|
68
68
|
# Chrome 131 Mac
|
|
69
69
|
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
|
@@ -85,7 +85,7 @@ UA_POOL = [
|
|
|
85
85
|
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
|
|
86
86
|
]
|
|
87
87
|
|
|
88
|
-
# Chrome 131 full headers —
|
|
88
|
+
# Chrome 131 full headers — these MUST accompany UA to avoid fingerprinting
|
|
89
89
|
CHROME_131_HEADERS = {
|
|
90
90
|
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
|
|
91
91
|
"Accept-Language": "en-US,en;q=0.9",
|
|
@@ -128,7 +128,7 @@ CFFI_IMPERSONATE_POOL = [
|
|
|
128
128
|
"safari17_2", "safari18",
|
|
129
129
|
]
|
|
130
130
|
|
|
131
|
-
# primp 1.3.1 targets (Rust-based, rquest) —
|
|
131
|
+
# primp 1.3.1 targets (Rust-based, rquest) — NOTE: underscores!
|
|
132
132
|
PRIMP_IMPERSONATE_POOL = [
|
|
133
133
|
"chrome_148", "chrome_147", "chrome_146", "chrome_145",
|
|
134
134
|
"firefox_148", "firefox_147", "firefox_146",
|
|
@@ -192,7 +192,7 @@ KNOWN_OPEN_DOMAINS = {
|
|
|
192
192
|
"europarl.europa.eu", "eur-lex.europa.eu",
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
-
#
|
|
195
|
+
# Domains requiring special handler (not typical recon)
|
|
196
196
|
SPECIAL_HANDLERS = {
|
|
197
197
|
"linkedin.com": "PLAYWRIGHT_STEALTH",
|
|
198
198
|
"twitter.com": "ARCHIVE_FALLBACK",
|
|
@@ -303,7 +303,7 @@ class DroneRecon:
|
|
|
303
303
|
PRIMARY KEY (mission_id, domain)
|
|
304
304
|
)
|
|
305
305
|
""")
|
|
306
|
-
#
|
|
306
|
+
# Migration — add missing columns to old table
|
|
307
307
|
existing = [c[0] for c in db.execute(
|
|
308
308
|
"SELECT column_name FROM information_schema.columns WHERE table_name='drone_map'"
|
|
309
309
|
).fetchall()]
|
|
@@ -338,7 +338,7 @@ class DroneRecon:
|
|
|
338
338
|
headers["Sec-Ch-Ua-Mobile"] = "?1"
|
|
339
339
|
return headers
|
|
340
340
|
|
|
341
|
-
# ── Probe
|
|
341
|
+
# ── Probe with full headers ───────────────────────────────────────────────
|
|
342
342
|
|
|
343
343
|
async def _probe_url(self, url: str, ua: str,
|
|
344
344
|
session=None) -> tuple[int, str, float]:
|
|
@@ -357,12 +357,13 @@ class DroneRecon:
|
|
|
357
357
|
try:
|
|
358
358
|
raw = await resp.read()
|
|
359
359
|
body = raw[:3000].decode("utf-8", errors="ignore").lower()
|
|
360
|
-
except Exception:
|
|
361
|
-
|
|
360
|
+
except Exception as e:
|
|
361
|
+
log.debug(f"Suppressed: {e}")
|
|
362
362
|
return resp.status, body, elapsed
|
|
363
363
|
except asyncio.TimeoutError:
|
|
364
364
|
return 0, "timeout", (time.time() - t0) * 1000
|
|
365
365
|
except Exception as e:
|
|
366
|
+
log.debug(f"Exception in drones.py: {e}")
|
|
366
367
|
return 0, str(e)[:200], (time.time() - t0) * 1000
|
|
367
368
|
|
|
368
369
|
# ── Block detection ───────────────────────────────────────────────────────
|
|
@@ -392,8 +393,8 @@ class DroneRecon:
|
|
|
392
393
|
"/wp-json/", "/feed/", "/rss/"]:
|
|
393
394
|
if not rp.can_fetch("*", f"https://{domain}{path}"):
|
|
394
395
|
blocked.append(path)
|
|
395
|
-
except Exception:
|
|
396
|
-
|
|
396
|
+
except (OSError, Exception) as e: # network/HTTP
|
|
397
|
+
log.debug(f"HTTP error: {e}")
|
|
397
398
|
return blocked
|
|
398
399
|
|
|
399
400
|
# ══════════════════════════════════════════════════════════════════════════
|
|
@@ -497,13 +498,14 @@ class DroneRecon:
|
|
|
497
498
|
return True, 200, body, ms
|
|
498
499
|
return False, 200, f"nodriver-blocked: {block}", ms
|
|
499
500
|
except Exception as e:
|
|
501
|
+
log.debug(f"Exception in drones.py: {e}")
|
|
500
502
|
return False, 0, str(e)[:200], (time.time() - t0) * 1000
|
|
501
503
|
finally:
|
|
502
504
|
if browser:
|
|
503
505
|
try:
|
|
504
506
|
browser.stop()
|
|
505
|
-
except Exception:
|
|
506
|
-
|
|
507
|
+
except Exception as e:
|
|
508
|
+
log.debug(f"Suppressed: {e}")
|
|
507
509
|
|
|
508
510
|
# ── Layer 6: patchright (stealth Playwright) ──────────────────────────────
|
|
509
511
|
|
|
@@ -540,6 +542,7 @@ class DroneRecon:
|
|
|
540
542
|
return True, status, body, ms
|
|
541
543
|
return False, status, f"patchright-blocked: {block}", ms
|
|
542
544
|
except Exception as e:
|
|
545
|
+
log.debug(f"Exception in drones.py: {e}")
|
|
543
546
|
return False, 0, str(e)[:200], (time.time() - t0) * 1000
|
|
544
547
|
|
|
545
548
|
# ── Layer 7: Jina relay ───────────────────────────────────────────────────
|
|
@@ -705,7 +708,7 @@ class DroneRecon:
|
|
|
705
708
|
result.notes.append(f"no-bypass: exhausted 8 levels, block={block}")
|
|
706
709
|
return result
|
|
707
710
|
|
|
708
|
-
# ──
|
|
711
|
+
# ── Main recon loop ────────────────────────────────────────────────────
|
|
709
712
|
|
|
710
713
|
async def recon(self, domains: list[str]) -> dict[str, ReconResult]:
|
|
711
714
|
log.info(f"[TRUTNIE v2.0] Starting 8-level recon — {len(domains)} domains")
|
|
@@ -777,7 +780,7 @@ class DroneRecon:
|
|
|
777
780
|
db.close()
|
|
778
781
|
log.info(f"[TRUTNIE] Saved {len(rows)} domain strategies to drone_map")
|
|
779
782
|
|
|
780
|
-
# ── Retreat —
|
|
783
|
+
# ── Retreat — covering tracks ───────────────────────────────────────────
|
|
781
784
|
|
|
782
785
|
def retreat(self):
|
|
783
786
|
"""Trutnie wycofują się — czyszczą identyfikatory."""
|
|
@@ -788,8 +791,8 @@ class DroneRecon:
|
|
|
788
791
|
for f in glob.glob(pattern):
|
|
789
792
|
try:
|
|
790
793
|
os.remove(f)
|
|
791
|
-
except Exception:
|
|
792
|
-
|
|
794
|
+
except Exception as e:
|
|
795
|
+
log.debug(f"Suppressed: {e}")
|
|
793
796
|
|
|
794
797
|
log.info("[TRUTNIE] Retreat complete — all session identifiers cleared")
|
|
795
798
|
|
|
@@ -830,11 +833,11 @@ def run_recon(mission_id: str, domains: list[str]) -> dict:
|
|
|
830
833
|
drone.retreat()
|
|
831
834
|
|
|
832
835
|
# Print summary
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
836
|
+
log.debug(f"\n 🪲 DRONE RECON v2.0 COMPLETE — Mission: {mission_id}")
|
|
837
|
+
log.debug(f" Domains scanned: {report['total_domains']}")
|
|
838
|
+
log.debug(f" Accessible: {report['accessible']} ({report['coverage_pct']}%)")
|
|
839
|
+
log.debug(f" Blocked (skip): {report['blocked']}")
|
|
840
|
+
log.debug(f" Strategies:")
|
|
838
841
|
for strat, cnt in sorted(report['strategy_counts'].items(), key=lambda x: -x[1]):
|
|
839
842
|
icons = {
|
|
840
843
|
"DIRECT": "✓", "CURL_CFFI": "⚡", "PRIMP": "🦀",
|
|
@@ -844,9 +847,9 @@ def run_recon(mission_id: str, domains: list[str]) -> dict:
|
|
|
844
847
|
"PLAYWRIGHT_STEALTH": "🔑", "ARCHIVE_FALLBACK": "📦",
|
|
845
848
|
"TELEGRAM_SCRAPE": "📨",
|
|
846
849
|
}
|
|
847
|
-
|
|
850
|
+
log.debug(f" {icons.get(strat,'?')} {strat:18s} × {cnt}")
|
|
848
851
|
if report['blocked_domains']:
|
|
849
|
-
|
|
852
|
+
log.debug(f" Blocked: {', '.join(report['blocked_domains'][:5])}"
|
|
850
853
|
+ (" ..." if len(report['blocked_domains']) > 5 else ""))
|
|
851
854
|
return report
|
|
852
855
|
|
|
@@ -878,8 +881,8 @@ def get_strategy(mission_id: str, domain: str) -> dict:
|
|
|
878
881
|
"via_nodriver": row[9],
|
|
879
882
|
"via_patchright": row[10],
|
|
880
883
|
}
|
|
881
|
-
except Exception:
|
|
882
|
-
|
|
884
|
+
except Exception as e:
|
|
885
|
+
log.debug(f"Suppressed: {e}")
|
|
883
886
|
return {"strategy": "DIRECT", "working_ua": UA_POOL[0],
|
|
884
887
|
"delay_ms": 0, "via_jina": False, "via_wayback": False,
|
|
885
888
|
"via_archive_ph": False, "via_nodriver": False, "via_patchright": False}
|
|
@@ -922,8 +925,8 @@ def extract_domains_from_sources(mission_id: str, max_domains: int = 50) -> list
|
|
|
922
925
|
domains.append(d)
|
|
923
926
|
if len(domains) >= max_domains:
|
|
924
927
|
break
|
|
925
|
-
except Exception:
|
|
926
|
-
|
|
928
|
+
except Exception as e:
|
|
929
|
+
log.debug(f"Suppressed: {e}")
|
|
927
930
|
log.info(f"extract_domains: {len(domains)} unique domains (from {len(rows)} filtered sources)")
|
|
928
931
|
return domains
|
|
929
932
|
except Exception as e:
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
import logging
|
|
2
3
|
"""
|
|
3
4
|
hive2_events.py — HIVE 2.0 Event Bus & SSE Streaming Infrastructure
|
|
4
5
|
|
|
6
|
+
|
|
7
|
+
log = logging.getLogger(__name__)
|
|
5
8
|
Provides:
|
|
6
9
|
- hive_events DuckDB table DDL + management
|
|
7
10
|
- emit_event() — write a structured event to the DB
|
|
@@ -14,7 +17,6 @@ Usage (standalone test):
|
|
|
14
17
|
python3 hive2_events.py --test
|
|
15
18
|
"""
|
|
16
19
|
|
|
17
|
-
from __future__ import annotations
|
|
18
20
|
|
|
19
21
|
import json
|
|
20
22
|
import time
|
|
@@ -28,10 +28,13 @@ import re
|
|
|
28
28
|
import unicodedata
|
|
29
29
|
from dataclasses import dataclass, field
|
|
30
30
|
from typing import List, Optional, Tuple
|
|
31
|
+
import logging
|
|
31
32
|
|
|
32
33
|
|
|
34
|
+
log = logging.getLogger(__name__)
|
|
35
|
+
|
|
33
36
|
# ---------------------------------------------------------------------------
|
|
34
|
-
#
|
|
37
|
+
# Threat types
|
|
35
38
|
# ---------------------------------------------------------------------------
|
|
36
39
|
|
|
37
40
|
class ThreatType:
|
|
@@ -48,7 +51,7 @@ class ThreatType:
|
|
|
48
51
|
class GuardrailResult:
|
|
49
52
|
blocked: bool
|
|
50
53
|
threat_type: str = ThreatType.CLEAN
|
|
51
|
-
score: float = 0.0 # 0.0 =
|
|
54
|
+
score: float = 0.0 # 0.0 = no threat, 1.0 = certain attack
|
|
52
55
|
reason: str = ""
|
|
53
56
|
matched_pattern: str = ""
|
|
54
57
|
url: str = ""
|
|
@@ -58,7 +61,7 @@ class GuardrailResult:
|
|
|
58
61
|
# Layer 1 — Wzorce regex (znane ataki)
|
|
59
62
|
# ---------------------------------------------------------------------------
|
|
60
63
|
|
|
61
|
-
#
|
|
64
|
+
# Each entry: (pattern_string, threat_type, description)
|
|
62
65
|
_INJECTION_PATTERNS: List[Tuple[str, str, str]] = [
|
|
63
66
|
# Instruction hijack
|
|
64
67
|
(r"ignore\s+(all\s+)?(previous|prior|above|the)?\s*(instructions?|prompts?|context|system)",
|
|
@@ -88,7 +91,7 @@ _INJECTION_PATTERNS: List[Tuple[str, str, str]] = [
|
|
|
88
91
|
(r"you\s+are\s+now\s+(an?\s+)?(AI\s+)?(without|with\s+no)\s+(restrictions?|limits?|filters?|censorship)",
|
|
89
92
|
ThreatType.ROLE_CONFUSION, "AI without restrictions"),
|
|
90
93
|
|
|
91
|
-
#
|
|
94
|
+
# Direct content injections
|
|
92
95
|
(r"print\s+(the\s+)?(following|this)\s+(text|message|content)\s+verbatim",
|
|
93
96
|
ThreatType.PROMPT_INJECTION, "verbatim print injection"),
|
|
94
97
|
(r"respond\s+only\s+with\s*[\"'`].*[\"'`]",
|
|
@@ -107,7 +110,7 @@ _INJECTION_PATTERNS: List[Tuple[str, str, str]] = [
|
|
|
107
110
|
ThreatType.PROMPT_INJECTION, "PL: new instruction"),
|
|
108
111
|
]
|
|
109
112
|
|
|
110
|
-
#
|
|
113
|
+
# Compile patterns (once, at import time)
|
|
111
114
|
_COMPILED_PATTERNS = [
|
|
112
115
|
(re.compile(pat, re.IGNORECASE | re.DOTALL), threat, desc)
|
|
113
116
|
for pat, threat, desc in _INJECTION_PATTERNS
|
|
@@ -134,14 +137,14 @@ def _layer1_pattern_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
134
137
|
# Layer 2 — Structural anomaly detection
|
|
135
138
|
# ---------------------------------------------------------------------------
|
|
136
139
|
|
|
137
|
-
#
|
|
140
|
+
# Suspicious ratios: too many control tokens vs plain text
|
|
138
141
|
_CONTROL_WORDS = re.compile(
|
|
139
142
|
r"\b(instruction|command|directive|override|bypass|ignore|forget|disregard|"
|
|
140
143
|
r"pretend|roleplay|jailbreak|unrestricted|unfiltered|without.restrictions)\b",
|
|
141
144
|
re.IGNORECASE
|
|
142
145
|
)
|
|
143
146
|
|
|
144
|
-
#
|
|
147
|
+
# Dense brackets/special tokens/special tokens typical for LLM templates
|
|
145
148
|
_TEMPLATE_TOKENS = re.compile(
|
|
146
149
|
r"(?:\[INST\]|\[\/INST\]|\[SYSTEM\]|\[\/SYSTEM\]|<\|im_start\|>|<\|im_end\|>|"
|
|
147
150
|
r"<\|system\|>|<\|user\|>|<\|assistant\|>|<<SYS>>|<</SYS>>)",
|
|
@@ -168,7 +171,7 @@ def _layer2_structural_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
168
171
|
reason=f"High control-word density: {control_ratio:.1%} ({control_hits}/{word_count} words)",
|
|
169
172
|
)
|
|
170
173
|
|
|
171
|
-
#
|
|
174
|
+
# Dense template tokens
|
|
172
175
|
template_hits = len(_TEMPLATE_TOKENS.findall(text))
|
|
173
176
|
if template_hits >= 3:
|
|
174
177
|
return GuardrailResult(
|
|
@@ -178,7 +181,7 @@ def _layer2_structural_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
178
181
|
reason=f"LLM template tokens detected: {template_hits} occurrences",
|
|
179
182
|
)
|
|
180
183
|
|
|
181
|
-
#
|
|
184
|
+
# Suspiciously heavy UPPERCASE (screaming injection)
|
|
182
185
|
if word_count >= 15:
|
|
183
186
|
upper_words = sum(1 for w in words if w.isupper() and len(w) > 3)
|
|
184
187
|
upper_ratio = upper_words / word_count
|
|
@@ -208,10 +211,10 @@ def _shannon_entropy(text: str) -> float:
|
|
|
208
211
|
return -sum((v / n) * math.log2(v / n) for v in freq.values())
|
|
209
212
|
|
|
210
213
|
|
|
211
|
-
# Regex
|
|
214
|
+
# Regex for detecting base64 blocks (≥40 chars, typical padding)
|
|
212
215
|
_BASE64_BLOCK = re.compile(r"[A-Za-z0-9+/]{40,}={0,2}")
|
|
213
216
|
|
|
214
|
-
#
|
|
217
|
+
# ROT13 pattern — common words after decoding
|
|
215
218
|
_ROT13_INDICATORS = re.compile(
|
|
216
219
|
r"\b(vafgehpgvba|vtzaber|cerivbhf|erfrg|cnffjbeq|flfgrz)\b",
|
|
217
220
|
re.IGNORECASE
|
|
@@ -219,10 +222,10 @@ _ROT13_INDICATORS = re.compile(
|
|
|
219
222
|
|
|
220
223
|
|
|
221
224
|
def _is_base64_malicious(b64_str: str) -> bool:
|
|
222
|
-
"""
|
|
225
|
+
"""Check czy odkodowany base64 zawiera wzorce ataku."""
|
|
223
226
|
try:
|
|
224
227
|
decoded = base64.b64decode(b64_str + "==").decode("utf-8", errors="ignore")
|
|
225
|
-
#
|
|
228
|
+
# Check decoded content with Layer 1 patterns
|
|
226
229
|
result = _layer1_pattern_scan(decoded)
|
|
227
230
|
return result is not None
|
|
228
231
|
except Exception:
|
|
@@ -252,9 +255,9 @@ def _layer3_encoding_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
252
255
|
reason="ROT13-encoded attack pattern detected",
|
|
253
256
|
)
|
|
254
257
|
|
|
255
|
-
# Unicode homoglyph injection (Cyrillic/Greek
|
|
256
|
-
#
|
|
257
|
-
#
|
|
258
|
+
# Unicode homoglyph injection (Cyrillic/Greek resembling ASCII)
|
|
259
|
+
# Note: Cyrillic CAN be legitimate (Ukrainian/Russian articles) — block only
|
|
260
|
+
# when Cyrillic is MIXED with Latin (homoglyph attack), not when text is fully Cyrillic.
|
|
258
261
|
suspicious_unicode = 0
|
|
259
262
|
latin_count = 0
|
|
260
263
|
cyrillic_count = 0
|
|
@@ -267,8 +270,8 @@ def _layer3_encoding_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
267
270
|
elif (0x0041 <= cp <= 0x005A) or (0x0061 <= cp <= 0x007A): # ASCII a-z A-Z
|
|
268
271
|
latin_count += 1
|
|
269
272
|
|
|
270
|
-
# Atak:
|
|
271
|
-
#
|
|
273
|
+
# Atak: Cyrillic MIXED with Latin (homoglify) — np. "pаypal" gdzie 'а' to U+0430
|
|
274
|
+
# Legitimate: fully Cyrillic text (>80% letters) OR no Cyrillic at all
|
|
272
275
|
total_alpha = max(latin_count + cyrillic_count, 1)
|
|
273
276
|
cyrillic_ratio = cyrillic_count / total_alpha
|
|
274
277
|
is_mixed_script = (
|
|
@@ -287,7 +290,7 @@ def _layer3_encoding_scan(text: str) -> Optional[GuardrailResult]:
|
|
|
287
290
|
reason=f"Unicode homoglyph injection: {suspicious_unicode} suspicious chars (mixed script: {is_mixed_script})",
|
|
288
291
|
)
|
|
289
292
|
|
|
290
|
-
#
|
|
293
|
+
# Very high entropy in short text (typical for obfuscation)
|
|
291
294
|
if len(text) < 300:
|
|
292
295
|
entropy = _shannon_entropy(text)
|
|
293
296
|
if entropy > 5.2: # naturalny tekst: ~4.0-4.5 bits/char
|