ether-core 0.1.0__py3-none-any.whl
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.
- ether/__init__.py +32 -0
- ether/assets/wordlists/common_dirs.txt.gz +0 -0
- ether/assets/wordlists/common_params.txt.gz +0 -0
- ether/assets/wordlists/common_passwords.txt.gz +0 -0
- ether/assets/wordlists/common_usernames.txt.gz +0 -0
- ether/assets/wordlists/subdomains_500.txt.gz +0 -0
- ether/cli/__init__.py +5 -0
- ether/cli/__main__.py +8 -0
- ether/cli/commands/__init__.py +1 -0
- ether/cli/commands/doctor.py +21 -0
- ether/cli/commands/graph.py +311 -0
- ether/cli/commands/logs.py +45 -0
- ether/cli/commands/mcp.py +49 -0
- ether/cli/commands/run.py +146 -0
- ether/cli/commands/session.py +61 -0
- ether/cli/commands/telemetry.py +51 -0
- ether/cli/commands/tool.py +131 -0
- ether/cli/context.py +71 -0
- ether/cli/formatters.py +39 -0
- ether/cli/router.py +368 -0
- ether/common/__init__.py +201 -0
- ether/common/algorithms.py +407 -0
- ether/common/canonicalize.py +93 -0
- ether/common/context.py +25 -0
- ether/common/crypto.py +183 -0
- ether/common/embeddings.py +93 -0
- ether/common/exceptions.py +13 -0
- ether/common/logging.py +386 -0
- ether/common/secure_memory.py +159 -0
- ether/common/ssrf.py +93 -0
- ether/core/__init__.py +25 -0
- ether/core/diagnostics.py +368 -0
- ether/core/executor.py +296 -0
- ether/core/sandbox.py +118 -0
- ether/core/session.py +956 -0
- ether/gateway/__init__.py +21 -0
- ether/gateway/gate.py +392 -0
- ether/gateway/network.py +98 -0
- ether/gateway/preflight.py +802 -0
- ether/graph/__init__.py +13 -0
- ether/graph/analytics.py +334 -0
- ether/graph/store.py +1615 -0
- ether/graph/telemetry.py +334 -0
- ether/graph/timeline.py +185 -0
- ether/mcp/__init__.py +5 -0
- ether/mcp/server.py +382 -0
- ether/paths.py +176 -0
- ether/py.typed +0 -0
- ether/registry/__init__.py +7 -0
- ether/registry/adapter.py +194 -0
- ether/registry/manifest.py +53 -0
- ether/registry/registry.py +150 -0
- ether/registry/wordlists.py +156 -0
- ether/schemas/__init__.py +50 -0
- ether/schemas/base.py +122 -0
- ether/schemas/credential.py +50 -0
- ether/schemas/dns.py +116 -0
- ether/schemas/host_internal.py +58 -0
- ether/schemas/network.py +142 -0
- ether/schemas/power.py +68 -0
- ether/schemas/vulnerability.py +221 -0
- ether/schemas/web.py +172 -0
- ether_core-0.1.0.dist-info/METADATA +440 -0
- ether_core-0.1.0.dist-info/RECORD +104 -0
- ether_core-0.1.0.dist-info/WHEEL +4 -0
- ether_core-0.1.0.dist-info/entry_points.txt +2 -0
- ether_core-0.1.0.dist-info/licenses/LICENSE +21 -0
- tools/__init__.py +0 -0
- tools/dnspython/__init__.py +1 -0
- tools/dnspython/adapter.py +302 -0
- tools/dnspython/cli.py +202 -0
- tools/dnspython/manifest.toml +138 -0
- tools/ffuf/__init__.py +1 -0
- tools/ffuf/adapter.py +183 -0
- tools/ffuf/manifest.toml +121 -0
- tools/gobuster/__init__.py +0 -0
- tools/gobuster/adapter.py +90 -0
- tools/gobuster/manifest.toml +104 -0
- tools/http_probe/adapter.py +256 -0
- tools/http_probe/manifest.toml +40 -0
- tools/netexec/__init__.py +1 -0
- tools/netexec/adapter.py +163 -0
- tools/netexec/manifest.toml +83 -0
- tools/nikto/__init__.py +0 -0
- tools/nikto/adapter.py +145 -0
- tools/nikto/manifest.toml +108 -0
- tools/nmap/__init__.py +0 -0
- tools/nmap/adapter.py +97 -0
- tools/nmap/manifest.toml +159 -0
- tools/nuclei/__init__.py +1 -0
- tools/nuclei/adapter.py +171 -0
- tools/nuclei/manifest.toml +117 -0
- tools/searchsploit/__init__.py +1 -0
- tools/searchsploit/adapter.py +139 -0
- tools/searchsploit/manifest.toml +103 -0
- tools/sqlmap/__init__.py +1 -0
- tools/sqlmap/adapter.py +214 -0
- tools/sqlmap/manifest.toml +89 -0
- tools/subfinder/__init__.py +0 -0
- tools/subfinder/adapter.py +71 -0
- tools/subfinder/manifest.toml +104 -0
- tools/whois/__init__.py +0 -0
- tools/whois/adapter.py +80 -0
- tools/whois/manifest.toml +95 -0
ether/graph/store.py
ADDED
|
@@ -0,0 +1,1615 @@
|
|
|
1
|
+
# PROTECTED FILE — See CONTRIBUTING.md before modifying.
|
|
2
|
+
# Changes to this file require team agreement.
|
|
3
|
+
"""SQLite-based graph store for workspaces and sessions."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import functools
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import logging
|
|
10
|
+
import os
|
|
11
|
+
import re
|
|
12
|
+
import uuid
|
|
13
|
+
from contextlib import asynccontextmanager
|
|
14
|
+
from datetime import UTC, datetime, timedelta
|
|
15
|
+
from typing import Any, Dict, List, Optional, Set
|
|
16
|
+
|
|
17
|
+
import aiosqlite
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import sqlite_vec
|
|
21
|
+
except ImportError:
|
|
22
|
+
sqlite_vec = None
|
|
23
|
+
|
|
24
|
+
from ether.common.embeddings import get_embedding_engine
|
|
25
|
+
from ether.graph.timeline import ActionTimelineRepository
|
|
26
|
+
from ether.schemas.base import BaseFinding
|
|
27
|
+
from ether.schemas.power import ActionRequest
|
|
28
|
+
|
|
29
|
+
logger = logging.getLogger(__name__)
|
|
30
|
+
|
|
31
|
+
SCHEMA_DDL = """
|
|
32
|
+
CREATE TABLE IF NOT EXISTS workspaces (
|
|
33
|
+
id TEXT PRIMARY KEY,
|
|
34
|
+
name TEXT NOT NULL,
|
|
35
|
+
status TEXT DEFAULT 'ACTIVE',
|
|
36
|
+
closed_at TIMESTAMP,
|
|
37
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
38
|
+
);
|
|
39
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
40
|
+
id TEXT PRIMARY KEY,
|
|
41
|
+
workspace_id TEXT NOT NULL,
|
|
42
|
+
name TEXT NOT NULL,
|
|
43
|
+
status TEXT DEFAULT 'ACTIVE',
|
|
44
|
+
closed_at TIMESTAMP,
|
|
45
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
46
|
+
FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE
|
|
47
|
+
);
|
|
48
|
+
CREATE TABLE IF NOT EXISTS nodes (
|
|
49
|
+
session_id TEXT NOT NULL,
|
|
50
|
+
id TEXT NOT NULL,
|
|
51
|
+
schema_type TEXT NOT NULL,
|
|
52
|
+
pik_json TEXT NOT NULL,
|
|
53
|
+
data_json TEXT NOT NULL,
|
|
54
|
+
status TEXT DEFAULT 'confirmed',
|
|
55
|
+
action_id TEXT,
|
|
56
|
+
created_action_id TEXT,
|
|
57
|
+
observation_count INTEGER DEFAULT 1,
|
|
58
|
+
ttl_seconds INTEGER DEFAULT 3600,
|
|
59
|
+
anchor_hash TEXT,
|
|
60
|
+
last_seen_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
61
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
62
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
63
|
+
PRIMARY KEY (session_id, id),
|
|
64
|
+
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
65
|
+
);
|
|
66
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
67
|
+
session_id TEXT NOT NULL,
|
|
68
|
+
source_id TEXT NOT NULL,
|
|
69
|
+
target_id TEXT NOT NULL,
|
|
70
|
+
relation_type TEXT NOT NULL,
|
|
71
|
+
action_id TEXT,
|
|
72
|
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
73
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
74
|
+
PRIMARY KEY (session_id, source_id, target_id, relation_type),
|
|
75
|
+
FOREIGN KEY (session_id, source_id) REFERENCES nodes(session_id, id) ON DELETE CASCADE,
|
|
76
|
+
FOREIGN KEY (session_id, target_id) REFERENCES nodes(session_id, id) ON DELETE CASCADE
|
|
77
|
+
);
|
|
78
|
+
CREATE TABLE IF NOT EXISTS event_log (
|
|
79
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
80
|
+
session_id TEXT NOT NULL,
|
|
81
|
+
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
82
|
+
action_payload TEXT,
|
|
83
|
+
result_payload TEXT,
|
|
84
|
+
human_readable TEXT,
|
|
85
|
+
schema_type TEXT,
|
|
86
|
+
finding_json TEXT,
|
|
87
|
+
closed INTEGER DEFAULT 0,
|
|
88
|
+
FOREIGN KEY (session_id) REFERENCES sessions(id) ON DELETE CASCADE
|
|
89
|
+
);
|
|
90
|
+
CREATE TABLE IF NOT EXISTS notes (
|
|
91
|
+
scope_type TEXT NOT NULL,
|
|
92
|
+
scope_id TEXT NOT NULL,
|
|
93
|
+
content TEXT DEFAULT '',
|
|
94
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
|
95
|
+
PRIMARY KEY (scope_type, scope_id)
|
|
96
|
+
);
|
|
97
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_session_schema ON nodes(session_id, schema_type);
|
|
98
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_anchor ON nodes(session_id, anchor_hash);
|
|
99
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_status ON nodes(session_id, status);
|
|
100
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_last_seen ON nodes(session_id, last_seen_at);
|
|
101
|
+
CREATE INDEX IF NOT EXISTS idx_edges_session ON edges(session_id);
|
|
102
|
+
CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(session_id, source_id);
|
|
103
|
+
CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(session_id, target_id);
|
|
104
|
+
CREATE INDEX IF NOT EXISTS idx_event_log_session_time ON event_log(session_id, timestamp DESC);
|
|
105
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_ws_status ON sessions(workspace_id, status);
|
|
106
|
+
CREATE INDEX IF NOT EXISTS idx_workspaces_status ON workspaces(status);
|
|
107
|
+
CREATE INDEX IF NOT EXISTS idx_notes_scope ON notes(scope_type, scope_id);
|
|
108
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_session_updated ON nodes(session_id, updated_at DESC);
|
|
109
|
+
CREATE INDEX IF NOT EXISTS idx_nodes_session_action ON nodes(session_id, action_id);
|
|
110
|
+
CREATE INDEX IF NOT EXISTS idx_edges_session_action ON edges(session_id, action_id);
|
|
111
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS vec_findings USING vec0(
|
|
112
|
+
node_id text primary key,
|
|
113
|
+
embedding float[384] distance_metric=cosine
|
|
114
|
+
);
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@functools.lru_cache(maxsize=4096)
|
|
119
|
+
def _cached_node_id(schema_type: str, pik_items: tuple) -> str:
|
|
120
|
+
"""Compute and cache deterministic SHA-256 node ID from sorted PIK items."""
|
|
121
|
+
pik_str = json.dumps(dict(pik_items), sort_keys=True)
|
|
122
|
+
return hashlib.sha256(f"{schema_type}:{pik_str}".encode()).hexdigest()
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class GraphStore:
|
|
126
|
+
"""Manages workspaces, sessions, and stateful entity graphs."""
|
|
127
|
+
|
|
128
|
+
def __init__(self, db_path: str):
|
|
129
|
+
self.db_path = db_path
|
|
130
|
+
self._on_upsert_callbacks = []
|
|
131
|
+
self._on_batch_callbacks = []
|
|
132
|
+
self._conn: Optional[aiosqlite.Connection] = None
|
|
133
|
+
self._lock: Optional[asyncio.Lock] = None
|
|
134
|
+
self._closed: bool = False
|
|
135
|
+
self._session_bloom: Dict[str, Any] = {}
|
|
136
|
+
self._warmed_sessions: Set[str] = set()
|
|
137
|
+
self.timeline = ActionTimelineRepository(self)
|
|
138
|
+
|
|
139
|
+
def _get_lock(self) -> asyncio.Lock:
|
|
140
|
+
if self._lock is None:
|
|
141
|
+
self._lock = asyncio.Lock()
|
|
142
|
+
return self._lock
|
|
143
|
+
|
|
144
|
+
def _get_bloom(self, session_id: str):
|
|
145
|
+
"""Get or initialize in-memory Bloom filter for fast node ID pre-filtering."""
|
|
146
|
+
from ether.common.algorithms import BloomFilter
|
|
147
|
+
|
|
148
|
+
if session_id not in self._session_bloom:
|
|
149
|
+
self._session_bloom[session_id] = BloomFilter(capacity=25000, error_rate=0.01)
|
|
150
|
+
return self._session_bloom[session_id]
|
|
151
|
+
|
|
152
|
+
def on_upsert(self, callback):
|
|
153
|
+
"""Register an async callback to fire when any finding is upserted."""
|
|
154
|
+
self._on_upsert_callbacks.append(callback)
|
|
155
|
+
|
|
156
|
+
def on_findings_batch(self, callback):
|
|
157
|
+
"""Register an async callback to fire when a batch of findings is upserted."""
|
|
158
|
+
self._on_batch_callbacks.append(callback)
|
|
159
|
+
|
|
160
|
+
@asynccontextmanager
|
|
161
|
+
async def connection(self):
|
|
162
|
+
"""Public context manager for acquiring a database connection."""
|
|
163
|
+
async with self._get_conn() as conn:
|
|
164
|
+
yield conn
|
|
165
|
+
|
|
166
|
+
@asynccontextmanager
|
|
167
|
+
async def _get_conn(self):
|
|
168
|
+
"""Helper to get a connection, supporting persistent connection for all paths."""
|
|
169
|
+
if self._closed:
|
|
170
|
+
raise ValueError("Cannot operate on a closed database.")
|
|
171
|
+
async with self._get_lock():
|
|
172
|
+
if self._conn is None:
|
|
173
|
+
if self.db_path != ":memory:":
|
|
174
|
+
db_dir = os.path.dirname(os.path.abspath(self.db_path))
|
|
175
|
+
if db_dir:
|
|
176
|
+
os.makedirs(db_dir, exist_ok=True)
|
|
177
|
+
self._conn = await aiosqlite.connect(self.db_path)
|
|
178
|
+
if sqlite_vec is not None:
|
|
179
|
+
try:
|
|
180
|
+
await self._conn.enable_load_extension(True)
|
|
181
|
+
await self._conn.load_extension(sqlite_vec.loadable_path())
|
|
182
|
+
await self._conn.enable_load_extension(False)
|
|
183
|
+
except Exception as e:
|
|
184
|
+
logger.warning(f"Could not load sqlite-vec extension: {e}")
|
|
185
|
+
await self._conn.execute("PRAGMA foreign_keys = ON")
|
|
186
|
+
await self._conn.execute("PRAGMA trusted_schema = OFF")
|
|
187
|
+
await self._conn.execute("PRAGMA busy_timeout = 5000")
|
|
188
|
+
if self.db_path != ":memory:":
|
|
189
|
+
await self._conn.execute("PRAGMA journal_mode = WAL")
|
|
190
|
+
await self._conn.execute("PRAGMA synchronous = NORMAL")
|
|
191
|
+
if self.db_path != ":memory:" and os.path.exists(self.db_path):
|
|
192
|
+
try:
|
|
193
|
+
os.chmod(self.db_path, 0o600)
|
|
194
|
+
except OSError:
|
|
195
|
+
pass
|
|
196
|
+
yield self._conn
|
|
197
|
+
|
|
198
|
+
async def _migrate_schema(self, db: aiosqlite.Connection) -> None:
|
|
199
|
+
"""Apply non-destructive schema migrations for existing databases."""
|
|
200
|
+
cursor = await db.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
|
201
|
+
existing_tables = {row[0] for row in await cursor.fetchall()}
|
|
202
|
+
|
|
203
|
+
table_columns = {
|
|
204
|
+
"nodes": [
|
|
205
|
+
("action_id", "TEXT"),
|
|
206
|
+
("created_action_id", "TEXT"),
|
|
207
|
+
("observation_count", "INTEGER DEFAULT 1"),
|
|
208
|
+
("ttl_seconds", "INTEGER DEFAULT 3600"),
|
|
209
|
+
("anchor_hash", "TEXT"),
|
|
210
|
+
("last_seen_at", "TIMESTAMP DEFAULT CURRENT_TIMESTAMP"),
|
|
211
|
+
("created_at", "TIMESTAMP DEFAULT CURRENT_TIMESTAMP"),
|
|
212
|
+
("updated_at", "TIMESTAMP DEFAULT CURRENT_TIMESTAMP"),
|
|
213
|
+
],
|
|
214
|
+
"edges": [
|
|
215
|
+
("action_id", "TEXT"),
|
|
216
|
+
("created_at", "TIMESTAMP DEFAULT CURRENT_TIMESTAMP"),
|
|
217
|
+
("updated_at", "TIMESTAMP DEFAULT CURRENT_TIMESTAMP"),
|
|
218
|
+
],
|
|
219
|
+
"event_log": [
|
|
220
|
+
("closed", "INTEGER DEFAULT 0"),
|
|
221
|
+
],
|
|
222
|
+
"sessions": [
|
|
223
|
+
("closed_at", "TIMESTAMP"),
|
|
224
|
+
],
|
|
225
|
+
"workspaces": [
|
|
226
|
+
("closed_at", "TIMESTAMP"),
|
|
227
|
+
],
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
for table, cols in table_columns.items():
|
|
231
|
+
if table in existing_tables:
|
|
232
|
+
col_cursor = await db.execute(f"PRAGMA table_info({table})")
|
|
233
|
+
existing_cols = {col_row[1] for col_row in await col_cursor.fetchall()}
|
|
234
|
+
for col_name, col_def in cols:
|
|
235
|
+
if col_name not in existing_cols:
|
|
236
|
+
await db.execute(f"ALTER TABLE {table} ADD COLUMN {col_name} {col_def}")
|
|
237
|
+
|
|
238
|
+
async def initialize(self):
|
|
239
|
+
"""Create tables and indices if they don't exist, applying migrations if needed."""
|
|
240
|
+
async with self._get_conn() as db:
|
|
241
|
+
await self._migrate_schema(db)
|
|
242
|
+
await db.executescript(SCHEMA_DDL)
|
|
243
|
+
await db.commit()
|
|
244
|
+
|
|
245
|
+
async def check_integrity(self) -> tuple[str, list[str]]:
|
|
246
|
+
"""Run an SQLite integrity check and return status and table list."""
|
|
247
|
+
async with self._get_conn() as db:
|
|
248
|
+
cursor = await db.execute("PRAGMA integrity_check")
|
|
249
|
+
row = await cursor.fetchone()
|
|
250
|
+
integrity_status = row[0] if row else "unknown"
|
|
251
|
+
|
|
252
|
+
cursor = await db.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
|
253
|
+
tables = [r[0] for r in await cursor.fetchall()]
|
|
254
|
+
return integrity_status, tables
|
|
255
|
+
|
|
256
|
+
async def close(self):
|
|
257
|
+
"""Close the persistent connection if it exists."""
|
|
258
|
+
self._closed = True
|
|
259
|
+
if self._conn:
|
|
260
|
+
try:
|
|
261
|
+
await self._conn.close()
|
|
262
|
+
except Exception:
|
|
263
|
+
pass
|
|
264
|
+
self._conn = None
|
|
265
|
+
|
|
266
|
+
async def get_or_create_default_session(self) -> tuple[str, str]:
|
|
267
|
+
"""Ensure the default workspace and session exist and return their IDs (ws_id, sess_id)."""
|
|
268
|
+
async with self._get_conn() as db:
|
|
269
|
+
db.row_factory = aiosqlite.Row
|
|
270
|
+
# 1. Check for existing Default Workspace
|
|
271
|
+
cursor = await db.execute(
|
|
272
|
+
"SELECT id FROM workspaces WHERE name = 'Default Workspace' LIMIT 1"
|
|
273
|
+
)
|
|
274
|
+
row = await cursor.fetchone()
|
|
275
|
+
if row:
|
|
276
|
+
ws_id = row["id"]
|
|
277
|
+
else:
|
|
278
|
+
ws_id = str(uuid.uuid4())
|
|
279
|
+
await db.execute(
|
|
280
|
+
"INSERT INTO workspaces (id, name, status) VALUES (?, ?, ?)",
|
|
281
|
+
(ws_id, "Default Workspace", "SYSTEM"),
|
|
282
|
+
)
|
|
283
|
+
|
|
284
|
+
# 2. Check for existing Default Session
|
|
285
|
+
cursor = await db.execute(
|
|
286
|
+
"SELECT id FROM sessions WHERE workspace_id = ? AND name = 'Default Session' LIMIT 1",
|
|
287
|
+
(ws_id,),
|
|
288
|
+
)
|
|
289
|
+
row = await cursor.fetchone()
|
|
290
|
+
if row:
|
|
291
|
+
sess_id = row["id"]
|
|
292
|
+
else:
|
|
293
|
+
sess_id = str(uuid.uuid4())
|
|
294
|
+
await db.execute(
|
|
295
|
+
"INSERT INTO sessions (id, workspace_id, name, status) VALUES (?, ?, ?, ?)",
|
|
296
|
+
(sess_id, ws_id, "Default Session", "SYSTEM"),
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
await db.commit()
|
|
300
|
+
return ws_id, sess_id
|
|
301
|
+
|
|
302
|
+
# --- Workspace Management ---
|
|
303
|
+
|
|
304
|
+
async def create_workspace(self, name: str) -> str:
|
|
305
|
+
workspace_id = str(uuid.uuid4())
|
|
306
|
+
async with self._get_conn() as db:
|
|
307
|
+
await db.execute(
|
|
308
|
+
"INSERT INTO workspaces (id, name) VALUES (?, ?)", (workspace_id, name)
|
|
309
|
+
)
|
|
310
|
+
await db.commit()
|
|
311
|
+
return workspace_id
|
|
312
|
+
|
|
313
|
+
async def rename_workspace(self, workspace_id: str, new_name: str) -> None:
|
|
314
|
+
async with self._get_conn() as db:
|
|
315
|
+
await db.execute(
|
|
316
|
+
"UPDATE workspaces SET name = ? WHERE id = ?", (new_name, workspace_id)
|
|
317
|
+
)
|
|
318
|
+
await db.commit()
|
|
319
|
+
|
|
320
|
+
async def list_workspaces(self, status_filter: Optional[str] = None) -> List[Dict]:
|
|
321
|
+
async with self._get_conn() as db:
|
|
322
|
+
db.row_factory = aiosqlite.Row
|
|
323
|
+
if status_filter:
|
|
324
|
+
cursor = await db.execute(
|
|
325
|
+
"SELECT * FROM workspaces WHERE status = ? ORDER BY created_at DESC",
|
|
326
|
+
(status_filter,),
|
|
327
|
+
)
|
|
328
|
+
else:
|
|
329
|
+
cursor = await db.execute("SELECT * FROM workspaces ORDER BY created_at DESC")
|
|
330
|
+
rows = await cursor.fetchall()
|
|
331
|
+
return [dict(r) for r in rows]
|
|
332
|
+
|
|
333
|
+
async def get_workspace(self, workspace_id: str) -> Optional[Dict]:
|
|
334
|
+
"""Get workspace metadata."""
|
|
335
|
+
async with self._get_conn() as db:
|
|
336
|
+
db.row_factory = aiosqlite.Row
|
|
337
|
+
cursor = await db.execute("SELECT * FROM workspaces WHERE id = ?", (workspace_id,))
|
|
338
|
+
row = await cursor.fetchone()
|
|
339
|
+
return dict(row) if row else None
|
|
340
|
+
|
|
341
|
+
async def close_workspace(self, workspace_id: str) -> None:
|
|
342
|
+
"""Mark workspace as closed/archived."""
|
|
343
|
+
async with self._get_conn() as db:
|
|
344
|
+
await db.execute(
|
|
345
|
+
"UPDATE workspaces SET status = 'CLOSED', closed_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
346
|
+
(workspace_id,),
|
|
347
|
+
)
|
|
348
|
+
await db.commit()
|
|
349
|
+
|
|
350
|
+
async def reopen_workspace(self, workspace_id: str) -> None:
|
|
351
|
+
"""Reopen a closed workspace."""
|
|
352
|
+
async with self._get_conn() as db:
|
|
353
|
+
await db.execute(
|
|
354
|
+
"UPDATE workspaces SET status = 'ACTIVE', closed_at = NULL WHERE id = ?",
|
|
355
|
+
(workspace_id,),
|
|
356
|
+
)
|
|
357
|
+
await db.commit()
|
|
358
|
+
|
|
359
|
+
# --- Session Management ---
|
|
360
|
+
|
|
361
|
+
async def create_session(
|
|
362
|
+
self, workspace_id: str, name: str, session_id: Optional[str] = None
|
|
363
|
+
) -> str:
|
|
364
|
+
actual_session_id = session_id or str(uuid.uuid4())
|
|
365
|
+
async with self._get_conn() as db:
|
|
366
|
+
await db.execute(
|
|
367
|
+
"INSERT INTO sessions (id, workspace_id, name) VALUES (?, ?, ?)",
|
|
368
|
+
(actual_session_id, workspace_id, name),
|
|
369
|
+
)
|
|
370
|
+
await db.commit()
|
|
371
|
+
return actual_session_id
|
|
372
|
+
|
|
373
|
+
async def rename_session(self, session_id: str, new_name: str) -> None:
|
|
374
|
+
async with self._get_conn() as db:
|
|
375
|
+
await db.execute("UPDATE sessions SET name = ? WHERE id = ?", (new_name, session_id))
|
|
376
|
+
await db.commit()
|
|
377
|
+
|
|
378
|
+
async def get_session(self, session_id: str) -> Optional[Dict]:
|
|
379
|
+
"""Get session metadata."""
|
|
380
|
+
async with self._get_conn() as db:
|
|
381
|
+
db.row_factory = aiosqlite.Row
|
|
382
|
+
cursor = await db.execute("SELECT * FROM sessions WHERE id = ?", (session_id,))
|
|
383
|
+
row = await cursor.fetchone()
|
|
384
|
+
return dict(row) if row else None
|
|
385
|
+
|
|
386
|
+
async def list_sessions(
|
|
387
|
+
self, workspace_id: str, status_filter: Optional[str] = None
|
|
388
|
+
) -> List[Dict]:
|
|
389
|
+
async with self._get_conn() as db:
|
|
390
|
+
db.row_factory = aiosqlite.Row
|
|
391
|
+
if status_filter:
|
|
392
|
+
cursor = await db.execute(
|
|
393
|
+
"SELECT * FROM sessions WHERE workspace_id = ? AND status = ? ORDER BY created_at DESC",
|
|
394
|
+
(workspace_id, status_filter),
|
|
395
|
+
)
|
|
396
|
+
else:
|
|
397
|
+
cursor = await db.execute(
|
|
398
|
+
"SELECT * FROM sessions WHERE workspace_id = ? ORDER BY created_at DESC",
|
|
399
|
+
(workspace_id,),
|
|
400
|
+
)
|
|
401
|
+
rows = await cursor.fetchall()
|
|
402
|
+
return [dict(r) for r in rows]
|
|
403
|
+
|
|
404
|
+
async def close_session(self, session_id: str) -> None:
|
|
405
|
+
"""Mark session as closed/archived."""
|
|
406
|
+
async with self._get_conn() as db:
|
|
407
|
+
await db.execute(
|
|
408
|
+
"UPDATE sessions SET status = 'CLOSED', closed_at = CURRENT_TIMESTAMP WHERE id = ?",
|
|
409
|
+
(session_id,),
|
|
410
|
+
)
|
|
411
|
+
await db.commit()
|
|
412
|
+
|
|
413
|
+
async def reopen_session(self, session_id: str) -> None:
|
|
414
|
+
"""Reopen an archived session back to ACTIVE."""
|
|
415
|
+
async with self._get_conn() as db:
|
|
416
|
+
await db.execute(
|
|
417
|
+
"UPDATE sessions SET status = 'ACTIVE', closed_at = NULL WHERE id = ?",
|
|
418
|
+
(session_id,),
|
|
419
|
+
)
|
|
420
|
+
await db.commit()
|
|
421
|
+
|
|
422
|
+
async def delete_workspace(self, workspace_id: str):
|
|
423
|
+
"""Delete a workspace and all its sessions/graphs (cascade)."""
|
|
424
|
+
async with self._get_conn() as db:
|
|
425
|
+
await db.execute("PRAGMA foreign_keys = ON")
|
|
426
|
+
if sqlite_vec is not None:
|
|
427
|
+
try:
|
|
428
|
+
await db.execute(
|
|
429
|
+
"""DELETE FROM vec_findings WHERE node_id IN (
|
|
430
|
+
SELECT n.id FROM nodes n
|
|
431
|
+
JOIN sessions s ON n.session_id = s.id
|
|
432
|
+
WHERE s.workspace_id = ?
|
|
433
|
+
)""",
|
|
434
|
+
(workspace_id,),
|
|
435
|
+
)
|
|
436
|
+
except Exception as e:
|
|
437
|
+
logger.warning(f"Error deleting workspace vectors: {e}")
|
|
438
|
+
await db.execute(
|
|
439
|
+
"""
|
|
440
|
+
DELETE FROM notes
|
|
441
|
+
WHERE scope_type IN ('session', 'learning')
|
|
442
|
+
AND scope_id IN (SELECT id FROM sessions WHERE workspace_id = ?)
|
|
443
|
+
""",
|
|
444
|
+
(workspace_id,),
|
|
445
|
+
)
|
|
446
|
+
await db.execute(
|
|
447
|
+
"DELETE FROM notes WHERE scope_type = 'workspace' AND scope_id = ?",
|
|
448
|
+
(workspace_id,),
|
|
449
|
+
)
|
|
450
|
+
await db.execute("DELETE FROM workspaces WHERE id = ?", (workspace_id,))
|
|
451
|
+
await db.commit()
|
|
452
|
+
|
|
453
|
+
async def delete_session(self, session_id: str):
|
|
454
|
+
"""Delete a single session, its graph data, and its notes."""
|
|
455
|
+
async with self._get_conn() as db:
|
|
456
|
+
await db.execute("PRAGMA foreign_keys = ON")
|
|
457
|
+
if sqlite_vec is not None:
|
|
458
|
+
try:
|
|
459
|
+
await db.execute(
|
|
460
|
+
"DELETE FROM vec_findings WHERE node_id IN (SELECT id FROM nodes WHERE session_id = ?)",
|
|
461
|
+
(session_id,),
|
|
462
|
+
)
|
|
463
|
+
except Exception as e:
|
|
464
|
+
logger.warning(f"Error deleting session vectors: {e}")
|
|
465
|
+
await db.execute("DELETE FROM sessions WHERE id = ?", (session_id,))
|
|
466
|
+
await db.execute(
|
|
467
|
+
"DELETE FROM notes WHERE (scope_type = 'session' AND scope_id = ?) OR (scope_type = 'learning' AND scope_id = ?)",
|
|
468
|
+
(session_id, session_id),
|
|
469
|
+
)
|
|
470
|
+
await db.commit()
|
|
471
|
+
|
|
472
|
+
# --- Notes Management ---
|
|
473
|
+
|
|
474
|
+
async def get_notes(self, scope_type: str, scope_id: str) -> str:
|
|
475
|
+
"""Fetch persistent notes for a specific scope (e.g. 'session' or 'learning')."""
|
|
476
|
+
async with self._get_conn() as db:
|
|
477
|
+
cursor = await db.execute(
|
|
478
|
+
"SELECT content FROM notes WHERE scope_type = ? AND scope_id = ?",
|
|
479
|
+
(scope_type, str(scope_id)),
|
|
480
|
+
)
|
|
481
|
+
row = await cursor.fetchone()
|
|
482
|
+
return row[0] if row and row[0] is not None else ""
|
|
483
|
+
|
|
484
|
+
async def save_notes(self, scope_type: str, scope_id: str, content: str) -> None:
|
|
485
|
+
"""Atomically persist notes for a specific scope in SQLite."""
|
|
486
|
+
async with self._get_conn() as db:
|
|
487
|
+
await db.execute(
|
|
488
|
+
"""
|
|
489
|
+
INSERT INTO notes (scope_type, scope_id, content, updated_at)
|
|
490
|
+
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
|
491
|
+
ON CONFLICT(scope_type, scope_id) DO UPDATE SET
|
|
492
|
+
content = excluded.content,
|
|
493
|
+
updated_at = CURRENT_TIMESTAMP
|
|
494
|
+
""",
|
|
495
|
+
(scope_type, str(scope_id), content),
|
|
496
|
+
)
|
|
497
|
+
await db.commit()
|
|
498
|
+
|
|
499
|
+
async def move_session(self, session_id: str, target_workspace_id: str):
|
|
500
|
+
"""Move a session to a different workspace."""
|
|
501
|
+
async with self._get_conn() as db:
|
|
502
|
+
await db.execute(
|
|
503
|
+
"UPDATE sessions SET workspace_id = ? WHERE id = ?",
|
|
504
|
+
(target_workspace_id, session_id),
|
|
505
|
+
)
|
|
506
|
+
await db.commit()
|
|
507
|
+
|
|
508
|
+
async def get_recent_activity(self, workspace_id: str, limit: int = 5) -> List[Dict]:
|
|
509
|
+
"""Fetch latest events across all sessions in a workspace."""
|
|
510
|
+
async with self._get_conn() as db:
|
|
511
|
+
db.row_factory = aiosqlite.Row
|
|
512
|
+
query = """
|
|
513
|
+
SELECT e.*, s.name as session_name
|
|
514
|
+
FROM event_log e
|
|
515
|
+
JOIN sessions s ON e.session_id = s.id
|
|
516
|
+
WHERE s.workspace_id = ? AND (e.closed IS NULL OR e.closed = 0)
|
|
517
|
+
ORDER BY e.timestamp DESC LIMIT ?
|
|
518
|
+
"""
|
|
519
|
+
cursor = await db.execute(query, (workspace_id, limit))
|
|
520
|
+
rows = await cursor.fetchall()
|
|
521
|
+
return [dict(r) for r in rows]
|
|
522
|
+
|
|
523
|
+
# --- Graph Data Persistence (Session Aware) ---
|
|
524
|
+
|
|
525
|
+
def generate_node_id(self, schema_type: str, pik: Dict[str, Any]) -> str:
|
|
526
|
+
"""Deterministically compute entity node ID from schema type and primary identity keys."""
|
|
527
|
+
try:
|
|
528
|
+
items = tuple(sorted(pik.items()))
|
|
529
|
+
return _cached_node_id(schema_type, items)
|
|
530
|
+
except TypeError:
|
|
531
|
+
pik_str = json.dumps(pik, sort_keys=True)
|
|
532
|
+
return hashlib.sha256(f"{schema_type}:{pik_str}".encode()).hexdigest()
|
|
533
|
+
|
|
534
|
+
async def upsert_findings_batch(
|
|
535
|
+
self, session_id: str, findings: List[BaseFinding], action_id: Optional[str] = None
|
|
536
|
+
) -> List[str]:
|
|
537
|
+
"""Atomically upsert a batch of findings in a single SQLite transaction."""
|
|
538
|
+
if not findings:
|
|
539
|
+
return []
|
|
540
|
+
|
|
541
|
+
node_ids: List[str] = []
|
|
542
|
+
event_log_params = []
|
|
543
|
+
unique_node_ids: List[str] = []
|
|
544
|
+
seen = set()
|
|
545
|
+
node_metadata: Dict[str, Dict[str, Any]] = {}
|
|
546
|
+
|
|
547
|
+
parent_nodes: Dict[str, tuple] = {}
|
|
548
|
+
parent_edges: set = set()
|
|
549
|
+
assoc_nodes: Dict[str, tuple] = {}
|
|
550
|
+
assoc_edges: set = set()
|
|
551
|
+
|
|
552
|
+
for finding in findings:
|
|
553
|
+
node_id = self.generate_node_id(finding.schema_type, finding.pik)
|
|
554
|
+
node_ids.append(node_id)
|
|
555
|
+
|
|
556
|
+
event_log_params.append(
|
|
557
|
+
(
|
|
558
|
+
session_id,
|
|
559
|
+
finding.schema_type,
|
|
560
|
+
finding.model_dump_json(),
|
|
561
|
+
f"Discovered {finding.schema_type}",
|
|
562
|
+
"{}",
|
|
563
|
+
"{}",
|
|
564
|
+
)
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
anchor_hash = getattr(finding, "anchor_hash", None)
|
|
568
|
+
if not anchor_hash and isinstance(finding.data, dict):
|
|
569
|
+
for key in (
|
|
570
|
+
"anchor_hash",
|
|
571
|
+
"tls_cert_sha256",
|
|
572
|
+
"ssh_hostkey_fingerprint",
|
|
573
|
+
"favicon_hash",
|
|
574
|
+
"soa_serial",
|
|
575
|
+
):
|
|
576
|
+
val = finding.data.get(key)
|
|
577
|
+
if val:
|
|
578
|
+
prefix = (
|
|
579
|
+
"tls"
|
|
580
|
+
if "tls" in key
|
|
581
|
+
else (
|
|
582
|
+
"ssh"
|
|
583
|
+
if "ssh" in key
|
|
584
|
+
else (
|
|
585
|
+
"favicon"
|
|
586
|
+
if "favicon" in key
|
|
587
|
+
else ("soa" if "soa" in key else "")
|
|
588
|
+
)
|
|
589
|
+
)
|
|
590
|
+
)
|
|
591
|
+
anchor_hash = (
|
|
592
|
+
f"{prefix}:{val}"
|
|
593
|
+
if prefix and not str(val).startswith(f"{prefix}:")
|
|
594
|
+
else str(val)
|
|
595
|
+
)
|
|
596
|
+
break
|
|
597
|
+
|
|
598
|
+
ttl_seconds = getattr(finding, "ttl_seconds", 3600) or 3600
|
|
599
|
+
|
|
600
|
+
if node_id not in seen:
|
|
601
|
+
seen.add(node_id)
|
|
602
|
+
unique_node_ids.append(node_id)
|
|
603
|
+
node_metadata[node_id] = {
|
|
604
|
+
"schema_type": finding.schema_type,
|
|
605
|
+
"pik": finding.pik,
|
|
606
|
+
"data": dict(finding.data),
|
|
607
|
+
"status": finding.status,
|
|
608
|
+
"ttl_seconds": ttl_seconds,
|
|
609
|
+
"anchor_hash": anchor_hash,
|
|
610
|
+
}
|
|
611
|
+
else:
|
|
612
|
+
node_metadata[node_id]["data"].update(finding.data)
|
|
613
|
+
node_metadata[node_id]["status"] = finding.status
|
|
614
|
+
node_metadata[node_id]["ttl_seconds"] = ttl_seconds
|
|
615
|
+
if anchor_hash:
|
|
616
|
+
node_metadata[node_id]["anchor_hash"] = anchor_hash
|
|
617
|
+
|
|
618
|
+
if finding.parent:
|
|
619
|
+
p = finding.parent
|
|
620
|
+
parent_id = self.generate_node_id(p.target_type, p.target_pik)
|
|
621
|
+
parent_nodes[parent_id] = (
|
|
622
|
+
session_id,
|
|
623
|
+
parent_id,
|
|
624
|
+
p.target_type,
|
|
625
|
+
json.dumps(p.target_pik),
|
|
626
|
+
"{}",
|
|
627
|
+
)
|
|
628
|
+
parent_edges.add((session_id, parent_id, node_id, p.via))
|
|
629
|
+
|
|
630
|
+
for assoc in finding.associations:
|
|
631
|
+
assoc_id = self.generate_node_id(assoc.target_type, assoc.target_pik)
|
|
632
|
+
assoc_nodes[assoc_id] = (
|
|
633
|
+
session_id,
|
|
634
|
+
assoc_id,
|
|
635
|
+
assoc.target_type,
|
|
636
|
+
json.dumps(assoc.target_pik),
|
|
637
|
+
"{}",
|
|
638
|
+
)
|
|
639
|
+
assoc_edges.add((session_id, node_id, assoc_id, assoc.via))
|
|
640
|
+
|
|
641
|
+
bloom = self._get_bloom(session_id)
|
|
642
|
+
|
|
643
|
+
async with self._get_conn() as db:
|
|
644
|
+
# Warm up bloom filter for this session if newly accessed
|
|
645
|
+
if session_id not in self._warmed_sessions:
|
|
646
|
+
cursor = await db.execute(
|
|
647
|
+
"SELECT id FROM nodes WHERE session_id = ?", (session_id,)
|
|
648
|
+
)
|
|
649
|
+
rows = await cursor.fetchall()
|
|
650
|
+
for (nid,) in rows:
|
|
651
|
+
bloom.add(nid)
|
|
652
|
+
self._warmed_sessions.add(session_id)
|
|
653
|
+
|
|
654
|
+
# 1. Log the events in a single batch
|
|
655
|
+
await db.executemany(
|
|
656
|
+
"""INSERT INTO event_log (session_id, schema_type, finding_json, human_readable, action_payload, result_payload)
|
|
657
|
+
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
658
|
+
event_log_params,
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
# 2. Fetch existing data only for candidate node IDs that might exist in this session (via Bloom filter)
|
|
662
|
+
candidate_ids = [nid for nid in unique_node_ids if nid in bloom]
|
|
663
|
+
if candidate_ids:
|
|
664
|
+
for i in range(0, len(candidate_ids), 500):
|
|
665
|
+
chunk = candidate_ids[i : i + 500]
|
|
666
|
+
placeholders = ",".join("?" for _ in chunk)
|
|
667
|
+
query_parts = (
|
|
668
|
+
"SELECT id, data_json FROM nodes WHERE session_id = ? AND id IN (",
|
|
669
|
+
placeholders,
|
|
670
|
+
")",
|
|
671
|
+
)
|
|
672
|
+
select_sql = "".join(query_parts)
|
|
673
|
+
cursor = await db.execute(select_sql, [session_id, *chunk])
|
|
674
|
+
rows = await cursor.fetchall()
|
|
675
|
+
for r_id, r_data in rows:
|
|
676
|
+
if r_data:
|
|
677
|
+
merged = json.loads(r_data)
|
|
678
|
+
merged.update(node_metadata[r_id]["data"])
|
|
679
|
+
node_metadata[r_id]["data"] = merged
|
|
680
|
+
|
|
681
|
+
# 3. Batch upsert the nodes
|
|
682
|
+
nodes_params = [
|
|
683
|
+
(
|
|
684
|
+
session_id,
|
|
685
|
+
nid,
|
|
686
|
+
meta["schema_type"],
|
|
687
|
+
json.dumps(meta["pik"]),
|
|
688
|
+
json.dumps(meta["data"]),
|
|
689
|
+
meta["status"],
|
|
690
|
+
action_id,
|
|
691
|
+
action_id,
|
|
692
|
+
meta["ttl_seconds"],
|
|
693
|
+
meta["anchor_hash"],
|
|
694
|
+
)
|
|
695
|
+
for nid, meta in node_metadata.items()
|
|
696
|
+
]
|
|
697
|
+
await db.executemany(
|
|
698
|
+
"""INSERT INTO nodes (
|
|
699
|
+
session_id, id, schema_type, pik_json, data_json, status,
|
|
700
|
+
action_id, created_action_id, ttl_seconds, anchor_hash,
|
|
701
|
+
observation_count, last_seen_at
|
|
702
|
+
)
|
|
703
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)
|
|
704
|
+
ON CONFLICT(session_id, id) DO UPDATE SET
|
|
705
|
+
data_json = excluded.data_json,
|
|
706
|
+
status = excluded.status,
|
|
707
|
+
action_id = COALESCE(excluded.action_id, nodes.action_id),
|
|
708
|
+
observation_count = nodes.observation_count + 1,
|
|
709
|
+
ttl_seconds = excluded.ttl_seconds,
|
|
710
|
+
anchor_hash = COALESCE(excluded.anchor_hash, nodes.anchor_hash),
|
|
711
|
+
last_seen_at = CURRENT_TIMESTAMP,
|
|
712
|
+
updated_at = CURRENT_TIMESTAMP""",
|
|
713
|
+
nodes_params,
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
# 4. Handle Parent and Association Relations (Auto-wiring in consolidated batches)
|
|
717
|
+
rel_nodes = list(parent_nodes.values())
|
|
718
|
+
if assoc_nodes:
|
|
719
|
+
rel_nodes.extend(assoc_nodes.values())
|
|
720
|
+
if rel_nodes:
|
|
721
|
+
await db.executemany(
|
|
722
|
+
"""INSERT OR IGNORE INTO nodes (
|
|
723
|
+
session_id, id, schema_type, pik_json, data_json,
|
|
724
|
+
action_id, created_action_id, observation_count, ttl_seconds, last_seen_at
|
|
725
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 3600, CURRENT_TIMESTAMP)""",
|
|
726
|
+
[(r[0], r[1], r[2], r[3], r[4], action_id, action_id) for r in rel_nodes],
|
|
727
|
+
)
|
|
728
|
+
|
|
729
|
+
# 4.5 Invariant Identity Anchoring & Cross-IP Migration
|
|
730
|
+
migration_edges: set = set()
|
|
731
|
+
stale_migrated_node_ids: set = set()
|
|
732
|
+
migration_event_params = []
|
|
733
|
+
|
|
734
|
+
for nid, meta in node_metadata.items():
|
|
735
|
+
anchor = meta.get("anchor_hash")
|
|
736
|
+
if not anchor:
|
|
737
|
+
continue
|
|
738
|
+
cursor = await db.execute(
|
|
739
|
+
"""
|
|
740
|
+
SELECT n.id, n.status,
|
|
741
|
+
(SELECT 1 FROM edges e
|
|
742
|
+
WHERE e.session_id = n.session_id
|
|
743
|
+
AND e.source_id = n.id
|
|
744
|
+
AND e.target_id = ?
|
|
745
|
+
AND e.relation_type = 'anchored_identity') as has_edge
|
|
746
|
+
FROM nodes n
|
|
747
|
+
WHERE n.session_id = ? AND n.anchor_hash = ? AND n.id != ?
|
|
748
|
+
ORDER BY n.updated_at DESC
|
|
749
|
+
""",
|
|
750
|
+
(nid, session_id, anchor, nid),
|
|
751
|
+
)
|
|
752
|
+
matching_nodes = await cursor.fetchall()
|
|
753
|
+
for old_id, old_status, has_edge in matching_nodes:
|
|
754
|
+
migration_edges.add((session_id, old_id, nid, "anchored_identity"))
|
|
755
|
+
if old_status != "stale":
|
|
756
|
+
stale_migrated_node_ids.add(old_id)
|
|
757
|
+
if not has_edge:
|
|
758
|
+
migration_event_params.append(
|
|
759
|
+
(
|
|
760
|
+
session_id,
|
|
761
|
+
"identity.migration",
|
|
762
|
+
json.dumps(
|
|
763
|
+
{
|
|
764
|
+
"anchor_hash": anchor,
|
|
765
|
+
"from_node_id": old_id,
|
|
766
|
+
"to_node_id": nid,
|
|
767
|
+
}
|
|
768
|
+
),
|
|
769
|
+
f"Anchored identity migration: {old_id} -> {nid} ({anchor})",
|
|
770
|
+
json.dumps({"action_id": action_id} if action_id else {}),
|
|
771
|
+
"{}",
|
|
772
|
+
)
|
|
773
|
+
)
|
|
774
|
+
|
|
775
|
+
if stale_migrated_node_ids:
|
|
776
|
+
placeholders = ",".join("?" for _ in stale_migrated_node_ids)
|
|
777
|
+
await db.execute(
|
|
778
|
+
f"UPDATE nodes SET status = 'stale', updated_at = CURRENT_TIMESTAMP WHERE session_id = ? AND id IN ({placeholders})",
|
|
779
|
+
[session_id, *stale_migrated_node_ids],
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
if migration_event_params:
|
|
783
|
+
await db.executemany(
|
|
784
|
+
"""INSERT INTO event_log (session_id, schema_type, finding_json, human_readable, action_payload, result_payload)
|
|
785
|
+
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
786
|
+
migration_event_params,
|
|
787
|
+
)
|
|
788
|
+
|
|
789
|
+
rel_edges = list(parent_edges | assoc_edges | migration_edges)
|
|
790
|
+
if rel_edges:
|
|
791
|
+
await db.executemany(
|
|
792
|
+
"""INSERT INTO edges (session_id, source_id, target_id, relation_type, action_id)
|
|
793
|
+
VALUES (?, ?, ?, ?, ?)
|
|
794
|
+
ON CONFLICT(session_id, source_id, target_id, relation_type) DO UPDATE SET
|
|
795
|
+
action_id = COALESCE(excluded.action_id, edges.action_id),
|
|
796
|
+
updated_at = CURRENT_TIMESTAMP""",
|
|
797
|
+
[(r[0], r[1], r[2], r[3], action_id) for r in rel_edges],
|
|
798
|
+
)
|
|
799
|
+
|
|
800
|
+
# 5. Vector Indexing in vec_findings (sqlite-vec)
|
|
801
|
+
if sqlite_vec is not None:
|
|
802
|
+
engine = get_embedding_engine()
|
|
803
|
+
vector_delete_ids = []
|
|
804
|
+
vector_params = []
|
|
805
|
+
seen_vec = set()
|
|
806
|
+
for finding in findings:
|
|
807
|
+
nid = self.generate_node_id(finding.schema_type, finding.pik)
|
|
808
|
+
if nid in seen_vec:
|
|
809
|
+
continue
|
|
810
|
+
seen_vec.add(nid)
|
|
811
|
+
try:
|
|
812
|
+
semantic_text = finding.to_semantic_text()
|
|
813
|
+
vec = engine.embed_text(semantic_text)
|
|
814
|
+
serialized = sqlite_vec.serialize_float32(vec)
|
|
815
|
+
vector_delete_ids.append((nid,))
|
|
816
|
+
vector_params.append((nid, serialized))
|
|
817
|
+
except Exception as e:
|
|
818
|
+
logger.warning(f"Could not compute semantic embedding for node {nid}: {e}")
|
|
819
|
+
|
|
820
|
+
if vector_params:
|
|
821
|
+
try:
|
|
822
|
+
await db.executemany(
|
|
823
|
+
"DELETE FROM vec_findings WHERE node_id = ?", vector_delete_ids
|
|
824
|
+
)
|
|
825
|
+
await db.executemany(
|
|
826
|
+
"INSERT INTO vec_findings(node_id, embedding) VALUES (?, ?)",
|
|
827
|
+
vector_params,
|
|
828
|
+
)
|
|
829
|
+
except Exception as e:
|
|
830
|
+
logger.warning(f"Error syncing vectors to vec_findings: {e}")
|
|
831
|
+
|
|
832
|
+
await db.commit()
|
|
833
|
+
|
|
834
|
+
# Update Bloom filter with all newly upserted node IDs and relationship nodes
|
|
835
|
+
for nid in unique_node_ids:
|
|
836
|
+
bloom.add(nid)
|
|
837
|
+
for p_nid in parent_nodes:
|
|
838
|
+
bloom.add(p_nid)
|
|
839
|
+
for a_nid in assoc_nodes:
|
|
840
|
+
bloom.add(a_nid)
|
|
841
|
+
|
|
842
|
+
# Trigger reactive callbacks
|
|
843
|
+
if self._on_batch_callbacks and findings:
|
|
844
|
+
for cb in self._on_batch_callbacks:
|
|
845
|
+
try:
|
|
846
|
+
await cb(session_id, findings)
|
|
847
|
+
except Exception as e:
|
|
848
|
+
logger.error(
|
|
849
|
+
f"Error in reactive batch callback {getattr(cb, '__name__', 'callback')}: {e}"
|
|
850
|
+
)
|
|
851
|
+
|
|
852
|
+
if self._on_upsert_callbacks and findings:
|
|
853
|
+
for finding in findings:
|
|
854
|
+
for cb in self._on_upsert_callbacks:
|
|
855
|
+
try:
|
|
856
|
+
await cb(session_id, finding)
|
|
857
|
+
except Exception as e:
|
|
858
|
+
logger.error(
|
|
859
|
+
f"Error in reactive callback {getattr(cb, '__name__', 'callback')}: {e}"
|
|
860
|
+
)
|
|
861
|
+
|
|
862
|
+
return node_ids
|
|
863
|
+
|
|
864
|
+
async def upsert_finding(
|
|
865
|
+
self, session_id: str, finding: BaseFinding, action_id: Optional[str] = None
|
|
866
|
+
) -> str:
|
|
867
|
+
"""Upsert a single finding (delegates to upsert_findings_batch)."""
|
|
868
|
+
node_ids = await self.upsert_findings_batch(session_id, [finding], action_id=action_id)
|
|
869
|
+
return node_ids[0] if node_ids else ""
|
|
870
|
+
|
|
871
|
+
async def query(
|
|
872
|
+
self,
|
|
873
|
+
schema_type: str,
|
|
874
|
+
session_id: Optional[str] = None,
|
|
875
|
+
include_stale: bool = False,
|
|
876
|
+
) -> List[Dict]:
|
|
877
|
+
"""Fetch all nodes of a specific schema type."""
|
|
878
|
+
async with self._get_conn() as db:
|
|
879
|
+
db.row_factory = aiosqlite.Row
|
|
880
|
+
conditions = ["schema_type = ?"]
|
|
881
|
+
params: list[Any] = [schema_type]
|
|
882
|
+
if session_id:
|
|
883
|
+
conditions.append("session_id = ?")
|
|
884
|
+
params.append(session_id)
|
|
885
|
+
if not include_stale:
|
|
886
|
+
conditions.append("status != 'stale'")
|
|
887
|
+
where_clause = " WHERE " + " AND ".join(conditions)
|
|
888
|
+
cursor = await db.execute(f"SELECT * FROM nodes{where_clause}", params)
|
|
889
|
+
rows = await cursor.fetchall()
|
|
890
|
+
return [dict(r) for r in rows]
|
|
891
|
+
|
|
892
|
+
async def get_event_log(self, session_id: str) -> List[Dict]:
|
|
893
|
+
"""Fetch all events for a session."""
|
|
894
|
+
return await self.timeline.get_event_log(session_id)
|
|
895
|
+
|
|
896
|
+
async def mark_event_closed(self, action_id: str, session_id: Optional[str] = None) -> None:
|
|
897
|
+
"""Mark an event log entry as closed/deleted."""
|
|
898
|
+
await self.timeline.mark_event_closed(action_id, session_id)
|
|
899
|
+
|
|
900
|
+
async def get_closed_events_count(self, session_id: str) -> int:
|
|
901
|
+
"""Get the count of closed events/tabs for a session."""
|
|
902
|
+
return await self.timeline.get_closed_events_count(session_id)
|
|
903
|
+
|
|
904
|
+
async def get_all_nodes(
|
|
905
|
+
self, session_id: str, schema_type: Optional[str] = None, include_stale: bool = False
|
|
906
|
+
) -> List[Dict]:
|
|
907
|
+
async with self._get_conn() as db:
|
|
908
|
+
db.row_factory = aiosqlite.Row
|
|
909
|
+
query = "SELECT * FROM nodes WHERE session_id = ?"
|
|
910
|
+
params: List[Any] = [session_id]
|
|
911
|
+
if not include_stale:
|
|
912
|
+
query += " AND status != 'stale'"
|
|
913
|
+
if schema_type:
|
|
914
|
+
query += " AND schema_type = ?"
|
|
915
|
+
params.append(schema_type)
|
|
916
|
+
query += " ORDER BY updated_at DESC"
|
|
917
|
+
cursor = await db.execute(query, params)
|
|
918
|
+
rows = await cursor.fetchall()
|
|
919
|
+
return [dict(r) for r in rows]
|
|
920
|
+
|
|
921
|
+
async def sync_vectors_batch(self, findings: List[BaseFinding]) -> int:
|
|
922
|
+
"""Compute and store offline vector embeddings for a batch of findings in vec_findings."""
|
|
923
|
+
if not findings or sqlite_vec is None:
|
|
924
|
+
return 0
|
|
925
|
+
engine = get_embedding_engine()
|
|
926
|
+
vector_delete_ids = []
|
|
927
|
+
vector_params = []
|
|
928
|
+
seen = set()
|
|
929
|
+
for finding in findings:
|
|
930
|
+
nid = self.generate_node_id(finding.schema_type, finding.pik)
|
|
931
|
+
if nid in seen:
|
|
932
|
+
continue
|
|
933
|
+
seen.add(nid)
|
|
934
|
+
try:
|
|
935
|
+
semantic_text = finding.to_semantic_text()
|
|
936
|
+
vec = engine.embed_text(semantic_text)
|
|
937
|
+
serialized = sqlite_vec.serialize_float32(vec)
|
|
938
|
+
vector_delete_ids.append((nid,))
|
|
939
|
+
vector_params.append((nid, serialized))
|
|
940
|
+
except Exception as e:
|
|
941
|
+
logger.warning(f"Could not compute semantic embedding for finding {nid}: {e}")
|
|
942
|
+
|
|
943
|
+
if not vector_params:
|
|
944
|
+
return 0
|
|
945
|
+
|
|
946
|
+
async with self._get_conn() as db:
|
|
947
|
+
await db.executemany("DELETE FROM vec_findings WHERE node_id = ?", vector_delete_ids)
|
|
948
|
+
await db.executemany(
|
|
949
|
+
"INSERT INTO vec_findings(node_id, embedding) VALUES (?, ?)", vector_params
|
|
950
|
+
)
|
|
951
|
+
await db.commit()
|
|
952
|
+
return len(vector_params)
|
|
953
|
+
|
|
954
|
+
async def semantic_search(
|
|
955
|
+
self,
|
|
956
|
+
session_id: str,
|
|
957
|
+
query: str,
|
|
958
|
+
limit: int = 10,
|
|
959
|
+
min_score: float = 0.0,
|
|
960
|
+
schema_type: Optional[str] = None,
|
|
961
|
+
include_stale: bool = False,
|
|
962
|
+
) -> List[Dict[str, Any]]:
|
|
963
|
+
"""Semantic search against session findings using offline vector embeddings.
|
|
964
|
+
|
|
965
|
+
Args:
|
|
966
|
+
session_id: Active session ID to scope the search.
|
|
967
|
+
query: Natural language query (e.g. 'Apache HTTP Server path traversal').
|
|
968
|
+
limit: Maximum number of findings to return.
|
|
969
|
+
min_score: Minimum cosine similarity score [0.0, 1.0].
|
|
970
|
+
schema_type: Optional filter by schema_type (e.g. 'network.service').
|
|
971
|
+
include_stale: Whether to include findings from stale nodes.
|
|
972
|
+
|
|
973
|
+
Returns:
|
|
974
|
+
List of matching finding node dictionaries ordered by descending similarity,
|
|
975
|
+
with added 'similarity' and 'distance' fields.
|
|
976
|
+
"""
|
|
977
|
+
if not query or not query.strip() or sqlite_vec is None:
|
|
978
|
+
return []
|
|
979
|
+
|
|
980
|
+
engine = get_embedding_engine()
|
|
981
|
+
query_vec = engine.embed_text(query)
|
|
982
|
+
serialized_query = sqlite_vec.serialize_float32(query_vec)
|
|
983
|
+
|
|
984
|
+
# Retrieve a generous candidate pool from vec0 (e.g. up to 10x limit or 100)
|
|
985
|
+
# to guarantee accurate ranking after session and schema filtering
|
|
986
|
+
k_candidates = max(limit * 10, 100)
|
|
987
|
+
|
|
988
|
+
async with self._get_conn() as db:
|
|
989
|
+
db.row_factory = aiosqlite.Row
|
|
990
|
+
|
|
991
|
+
sql = """
|
|
992
|
+
SELECT n.*, sub.distance
|
|
993
|
+
FROM (
|
|
994
|
+
SELECT node_id, distance
|
|
995
|
+
FROM vec_findings
|
|
996
|
+
WHERE embedding MATCH ? AND k = ?
|
|
997
|
+
) sub
|
|
998
|
+
JOIN nodes n ON sub.node_id = n.id
|
|
999
|
+
WHERE n.session_id = ?
|
|
1000
|
+
"""
|
|
1001
|
+
params: List[Any] = [serialized_query, k_candidates, session_id]
|
|
1002
|
+
|
|
1003
|
+
if not include_stale:
|
|
1004
|
+
sql += " AND n.status != 'stale'"
|
|
1005
|
+
|
|
1006
|
+
if schema_type:
|
|
1007
|
+
sql += " AND n.schema_type = ?"
|
|
1008
|
+
params.append(schema_type)
|
|
1009
|
+
|
|
1010
|
+
sql += " ORDER BY sub.distance ASC LIMIT ?"
|
|
1011
|
+
params.append(limit)
|
|
1012
|
+
|
|
1013
|
+
cursor = await db.execute(sql, params)
|
|
1014
|
+
rows = await cursor.fetchall()
|
|
1015
|
+
|
|
1016
|
+
results: List[Dict[str, Any]] = []
|
|
1017
|
+
for r in rows:
|
|
1018
|
+
item = dict(r)
|
|
1019
|
+
distance = item.get("distance", 1.0)
|
|
1020
|
+
similarity = max(0.0, min(1.0, 1.0 - distance))
|
|
1021
|
+
if similarity < min_score:
|
|
1022
|
+
continue
|
|
1023
|
+
item["similarity"] = round(similarity, 4)
|
|
1024
|
+
if isinstance(item.get("pik_json"), str):
|
|
1025
|
+
try:
|
|
1026
|
+
item["pik"] = json.loads(item["pik_json"])
|
|
1027
|
+
except Exception:
|
|
1028
|
+
pass
|
|
1029
|
+
if isinstance(item.get("data_json"), str):
|
|
1030
|
+
try:
|
|
1031
|
+
item["data"] = json.loads(item["data_json"])
|
|
1032
|
+
except Exception:
|
|
1033
|
+
pass
|
|
1034
|
+
results.append(item)
|
|
1035
|
+
|
|
1036
|
+
return results
|
|
1037
|
+
|
|
1038
|
+
async def reconcile_state_decay(
|
|
1039
|
+
self, session_id: str, now: Optional[datetime] = None
|
|
1040
|
+
) -> Dict[str, Any]:
|
|
1041
|
+
"""Deterministically evaluate and reconcile temporal state decay for a session.
|
|
1042
|
+
|
|
1043
|
+
Transitions:
|
|
1044
|
+
- confirmed -> stale (if elapsed > ttl and not flapping)
|
|
1045
|
+
- confirmed -> flapping (if elapsed > ttl and oscillations >= 2)
|
|
1046
|
+
- flapping -> stale (if elapsed > 2 * ttl)
|
|
1047
|
+
- proposed -> stale (if elapsed > ttl)
|
|
1048
|
+
- stale -> confirmed (if re-observed within ttl)
|
|
1049
|
+
"""
|
|
1050
|
+
if now is None:
|
|
1051
|
+
now = datetime.now(UTC)
|
|
1052
|
+
elif now.tzinfo is None:
|
|
1053
|
+
now = now.replace(tzinfo=UTC)
|
|
1054
|
+
|
|
1055
|
+
transitions = []
|
|
1056
|
+
updates = []
|
|
1057
|
+
|
|
1058
|
+
async with self._get_conn() as db:
|
|
1059
|
+
db.row_factory = aiosqlite.Row
|
|
1060
|
+
cursor = await db.execute(
|
|
1061
|
+
"SELECT id, status, observation_count, ttl_seconds, last_seen_at, data_json FROM nodes WHERE session_id = ?",
|
|
1062
|
+
(session_id,),
|
|
1063
|
+
)
|
|
1064
|
+
rows = await cursor.fetchall()
|
|
1065
|
+
|
|
1066
|
+
status_counts = {"confirmed": 0, "flapping": 0, "stale": 0, "proposed": 0}
|
|
1067
|
+
|
|
1068
|
+
for row in rows:
|
|
1069
|
+
nid = row["id"]
|
|
1070
|
+
current_status = row["status"] or "confirmed"
|
|
1071
|
+
ttl = int(row["ttl_seconds"] or 3600)
|
|
1072
|
+
last_seen_val = row["last_seen_at"]
|
|
1073
|
+
|
|
1074
|
+
last_seen_dt = now
|
|
1075
|
+
if last_seen_val:
|
|
1076
|
+
if isinstance(last_seen_val, str):
|
|
1077
|
+
dt_str = last_seen_val.replace("Z", "+00:00")
|
|
1078
|
+
if "T" not in dt_str and " " in dt_str:
|
|
1079
|
+
dt_str = dt_str.replace(" ", "T")
|
|
1080
|
+
try:
|
|
1081
|
+
parsed_dt = datetime.fromisoformat(dt_str)
|
|
1082
|
+
last_seen_dt = (
|
|
1083
|
+
parsed_dt.replace(tzinfo=UTC)
|
|
1084
|
+
if parsed_dt.tzinfo is None
|
|
1085
|
+
else parsed_dt
|
|
1086
|
+
)
|
|
1087
|
+
except Exception:
|
|
1088
|
+
last_seen_dt = now
|
|
1089
|
+
elif isinstance(last_seen_val, datetime):
|
|
1090
|
+
last_seen_dt = (
|
|
1091
|
+
last_seen_val.replace(tzinfo=UTC)
|
|
1092
|
+
if last_seen_val.tzinfo is None
|
|
1093
|
+
else last_seen_val
|
|
1094
|
+
)
|
|
1095
|
+
|
|
1096
|
+
elapsed = (now - last_seen_dt).total_seconds()
|
|
1097
|
+
|
|
1098
|
+
data = {}
|
|
1099
|
+
if row["data_json"]:
|
|
1100
|
+
try:
|
|
1101
|
+
data = json.loads(row["data_json"])
|
|
1102
|
+
except Exception:
|
|
1103
|
+
pass
|
|
1104
|
+
|
|
1105
|
+
oscillations = int(data.get("oscillations", 0)) if isinstance(data, dict) else 0
|
|
1106
|
+
is_flapping_indicator = (
|
|
1107
|
+
bool(data.get("flapping", False)) if isinstance(data, dict) else False
|
|
1108
|
+
)
|
|
1109
|
+
has_flapped = oscillations >= 2 or is_flapping_indicator
|
|
1110
|
+
|
|
1111
|
+
new_status = current_status
|
|
1112
|
+
|
|
1113
|
+
if elapsed > ttl:
|
|
1114
|
+
if current_status == "confirmed":
|
|
1115
|
+
new_status = "flapping" if has_flapped else "stale"
|
|
1116
|
+
elif current_status == "flapping":
|
|
1117
|
+
if elapsed > 2 * ttl:
|
|
1118
|
+
new_status = "stale"
|
|
1119
|
+
elif current_status == "proposed":
|
|
1120
|
+
new_status = "stale"
|
|
1121
|
+
|
|
1122
|
+
if new_status != current_status:
|
|
1123
|
+
transitions.append({"id": nid, "from": current_status, "to": new_status})
|
|
1124
|
+
updates.append((new_status, session_id, nid))
|
|
1125
|
+
status_counts[new_status] = status_counts.get(new_status, 0) + 1
|
|
1126
|
+
else:
|
|
1127
|
+
status_counts[current_status] = status_counts.get(current_status, 0) + 1
|
|
1128
|
+
|
|
1129
|
+
if updates:
|
|
1130
|
+
await db.executemany(
|
|
1131
|
+
"UPDATE nodes SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE session_id = ? AND id = ?",
|
|
1132
|
+
updates,
|
|
1133
|
+
)
|
|
1134
|
+
await db.commit()
|
|
1135
|
+
|
|
1136
|
+
return {
|
|
1137
|
+
"transitions": transitions,
|
|
1138
|
+
"status_breakdown": status_counts,
|
|
1139
|
+
"reconciled_count": len(transitions),
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
async def prune_stale_nodes(
|
|
1143
|
+
self, session_id: str, max_age_seconds: int = 604800, now: Optional[datetime] = None
|
|
1144
|
+
) -> int:
|
|
1145
|
+
"""Permanently delete stale nodes and their cascading edges older than max_age_seconds."""
|
|
1146
|
+
if now is None:
|
|
1147
|
+
now = datetime.now(UTC)
|
|
1148
|
+
elif now.tzinfo is None:
|
|
1149
|
+
now = now.replace(tzinfo=UTC)
|
|
1150
|
+
|
|
1151
|
+
cutoff = (now - timedelta(seconds=max_age_seconds)).strftime("%Y-%m-%d %H:%M:%S")
|
|
1152
|
+
|
|
1153
|
+
async with self._get_conn() as db:
|
|
1154
|
+
if sqlite_vec is not None:
|
|
1155
|
+
try:
|
|
1156
|
+
await db.execute(
|
|
1157
|
+
"""DELETE FROM vec_findings
|
|
1158
|
+
WHERE node_id IN (
|
|
1159
|
+
SELECT id FROM nodes
|
|
1160
|
+
WHERE session_id = ?
|
|
1161
|
+
AND status = 'stale'
|
|
1162
|
+
AND datetime(last_seen_at) < datetime(?)
|
|
1163
|
+
)""",
|
|
1164
|
+
(session_id, cutoff),
|
|
1165
|
+
)
|
|
1166
|
+
except Exception as e:
|
|
1167
|
+
logger.warning(f"Error purging stale vectors from vec_findings: {e}")
|
|
1168
|
+
cursor = await db.execute(
|
|
1169
|
+
"""DELETE FROM nodes
|
|
1170
|
+
WHERE session_id = ?
|
|
1171
|
+
AND status = 'stale'
|
|
1172
|
+
AND datetime(last_seen_at) < datetime(?)""",
|
|
1173
|
+
(session_id, cutoff),
|
|
1174
|
+
)
|
|
1175
|
+
await db.commit()
|
|
1176
|
+
return cursor.rowcount
|
|
1177
|
+
|
|
1178
|
+
async def get_anchored_migrations(
|
|
1179
|
+
self,
|
|
1180
|
+
session_id: str,
|
|
1181
|
+
action_id: Optional[str] = None,
|
|
1182
|
+
) -> List[Dict[str, str]]:
|
|
1183
|
+
"""Fetch anchored identity migrations recorded for a session."""
|
|
1184
|
+
async with self._get_conn() as db:
|
|
1185
|
+
db.row_factory = aiosqlite.Row
|
|
1186
|
+
query = """
|
|
1187
|
+
SELECT finding_json, timestamp, action_payload
|
|
1188
|
+
FROM event_log
|
|
1189
|
+
WHERE session_id = ? AND schema_type = 'identity.migration'
|
|
1190
|
+
ORDER BY timestamp ASC
|
|
1191
|
+
"""
|
|
1192
|
+
cursor = await db.execute(query, (session_id,))
|
|
1193
|
+
rows = await cursor.fetchall()
|
|
1194
|
+
migrations = []
|
|
1195
|
+
for r in rows:
|
|
1196
|
+
try:
|
|
1197
|
+
payload = json.loads(r["finding_json"])
|
|
1198
|
+
act_meta = json.loads(r["action_payload"]) if r["action_payload"] else {}
|
|
1199
|
+
if action_id and act_meta.get("action_id") != action_id:
|
|
1200
|
+
continue
|
|
1201
|
+
migrations.append(payload)
|
|
1202
|
+
except Exception:
|
|
1203
|
+
continue
|
|
1204
|
+
return migrations
|
|
1205
|
+
|
|
1206
|
+
async def get_all_edges(self, session_id: str) -> List[Dict]:
|
|
1207
|
+
async with self._get_conn() as db:
|
|
1208
|
+
db.row_factory = aiosqlite.Row
|
|
1209
|
+
cursor = await db.execute("SELECT * FROM edges WHERE session_id = ?", (session_id,))
|
|
1210
|
+
rows = await cursor.fetchall()
|
|
1211
|
+
return [dict(r) for r in rows]
|
|
1212
|
+
|
|
1213
|
+
async def get_workspace_nodes(self, workspace_id: str) -> List[Dict]:
|
|
1214
|
+
async with self._get_conn() as db:
|
|
1215
|
+
db.row_factory = aiosqlite.Row
|
|
1216
|
+
cursor = await db.execute(
|
|
1217
|
+
"""SELECT n.* FROM nodes n
|
|
1218
|
+
JOIN sessions s ON n.session_id = s.id
|
|
1219
|
+
WHERE s.workspace_id = ? ORDER BY n.updated_at DESC""",
|
|
1220
|
+
(workspace_id,),
|
|
1221
|
+
)
|
|
1222
|
+
rows = await cursor.fetchall()
|
|
1223
|
+
return [dict(r) for r in rows]
|
|
1224
|
+
|
|
1225
|
+
async def get_workspace_edges(self, workspace_id: str) -> List[Dict]:
|
|
1226
|
+
async with self._get_conn() as db:
|
|
1227
|
+
db.row_factory = aiosqlite.Row
|
|
1228
|
+
cursor = await db.execute(
|
|
1229
|
+
"""SELECT e.* FROM edges e
|
|
1230
|
+
JOIN sessions s ON e.session_id = s.id
|
|
1231
|
+
WHERE s.workspace_id = ?""",
|
|
1232
|
+
(workspace_id,),
|
|
1233
|
+
)
|
|
1234
|
+
rows = await cursor.fetchall()
|
|
1235
|
+
return [dict(r) for r in rows]
|
|
1236
|
+
|
|
1237
|
+
async def get_node(self, session_id: str, node_id: str) -> Optional[Dict]:
|
|
1238
|
+
"""Fetch a specific node by ID."""
|
|
1239
|
+
async with self._get_conn() as db:
|
|
1240
|
+
db.row_factory = aiosqlite.Row
|
|
1241
|
+
cursor = await db.execute(
|
|
1242
|
+
"SELECT * FROM nodes WHERE session_id = ? AND id = ?", (session_id, node_id)
|
|
1243
|
+
)
|
|
1244
|
+
row = await cursor.fetchone()
|
|
1245
|
+
return dict(row) if row else None
|
|
1246
|
+
|
|
1247
|
+
async def update_node_data(
|
|
1248
|
+
self, session_id: str, node_id: str, updates: Dict[str, Any]
|
|
1249
|
+
) -> None:
|
|
1250
|
+
"""Update fields inside a node's data_json (such as custom alias, name, or notes)."""
|
|
1251
|
+
async with self._get_conn() as db:
|
|
1252
|
+
cursor = await db.execute(
|
|
1253
|
+
"SELECT data_json FROM nodes WHERE session_id = ? AND id = ?", (session_id, node_id)
|
|
1254
|
+
)
|
|
1255
|
+
row = await cursor.fetchone()
|
|
1256
|
+
if not row:
|
|
1257
|
+
return
|
|
1258
|
+
current_data = json.loads(row[0] or "{}")
|
|
1259
|
+
current_data.update(updates)
|
|
1260
|
+
await db.execute(
|
|
1261
|
+
"UPDATE nodes SET data_json = ? WHERE session_id = ? AND id = ?",
|
|
1262
|
+
(json.dumps(current_data), session_id, node_id),
|
|
1263
|
+
)
|
|
1264
|
+
await db.commit()
|
|
1265
|
+
|
|
1266
|
+
async def get_stats(
|
|
1267
|
+
self, session_id: Optional[str] = None, workspace_id: Optional[str] = None
|
|
1268
|
+
) -> Dict[str, int]:
|
|
1269
|
+
async with self._get_conn() as db:
|
|
1270
|
+
if session_id:
|
|
1271
|
+
cursor = await db.execute(
|
|
1272
|
+
"SELECT schema_type, COUNT(*) FROM nodes WHERE session_id = ? GROUP BY schema_type",
|
|
1273
|
+
(session_id,),
|
|
1274
|
+
)
|
|
1275
|
+
elif workspace_id:
|
|
1276
|
+
cursor = await db.execute(
|
|
1277
|
+
"""SELECT n.schema_type, COUNT(*)
|
|
1278
|
+
FROM nodes n
|
|
1279
|
+
JOIN sessions s ON n.session_id = s.id
|
|
1280
|
+
WHERE s.workspace_id = ?
|
|
1281
|
+
GROUP BY n.schema_type""",
|
|
1282
|
+
(workspace_id,),
|
|
1283
|
+
)
|
|
1284
|
+
else:
|
|
1285
|
+
cursor = await db.execute(
|
|
1286
|
+
"SELECT schema_type, COUNT(*) FROM nodes GROUP BY schema_type"
|
|
1287
|
+
)
|
|
1288
|
+
|
|
1289
|
+
rows = await cursor.fetchall()
|
|
1290
|
+
stats = {"total": 0}
|
|
1291
|
+
for schema_type, count in rows:
|
|
1292
|
+
stats[schema_type] = count
|
|
1293
|
+
stats["total"] += count
|
|
1294
|
+
return stats
|
|
1295
|
+
|
|
1296
|
+
async def append_event(
|
|
1297
|
+
self, session_id: str, action: ActionRequest, result: Dict[str, Any], message: str
|
|
1298
|
+
):
|
|
1299
|
+
"""Append a structured action/result event to the log."""
|
|
1300
|
+
await self.timeline.append_event(session_id, action, result, message)
|
|
1301
|
+
|
|
1302
|
+
async def log_audit_event(
|
|
1303
|
+
self, session_id: str, action_name: str, message: str, status: str
|
|
1304
|
+
) -> None:
|
|
1305
|
+
"""Append an audit lifecycle event (e.g. session closed/reopened) to event_log."""
|
|
1306
|
+
await self.timeline.log_audit_event(session_id, action_name, message, status)
|
|
1307
|
+
|
|
1308
|
+
async def export_session(self, session_id: str, dest_db_path: str) -> None:
|
|
1309
|
+
"""Export session metadata, nodes, edges, and event_log rows to a new SQLite database."""
|
|
1310
|
+
dest_store = GraphStore(dest_db_path)
|
|
1311
|
+
await dest_store.initialize()
|
|
1312
|
+
await dest_store.close()
|
|
1313
|
+
|
|
1314
|
+
async with self._get_conn() as db:
|
|
1315
|
+
await db.execute("ATTACH DATABASE ? AS dest", (dest_db_path,))
|
|
1316
|
+
try:
|
|
1317
|
+
# 1. Copy workspace row
|
|
1318
|
+
await db.execute(
|
|
1319
|
+
"""
|
|
1320
|
+
INSERT OR IGNORE INTO dest.workspaces (id, name, status, created_at)
|
|
1321
|
+
SELECT w.id, w.name, w.status, w.created_at
|
|
1322
|
+
FROM workspaces w
|
|
1323
|
+
JOIN sessions s ON s.workspace_id = w.id
|
|
1324
|
+
WHERE s.id = ?
|
|
1325
|
+
""",
|
|
1326
|
+
(session_id,),
|
|
1327
|
+
)
|
|
1328
|
+
|
|
1329
|
+
# 2. Copy session row
|
|
1330
|
+
await db.execute(
|
|
1331
|
+
"""
|
|
1332
|
+
INSERT OR IGNORE INTO dest.sessions (id, workspace_id, name, status, created_at)
|
|
1333
|
+
SELECT id, workspace_id, name, status, created_at
|
|
1334
|
+
FROM sessions
|
|
1335
|
+
WHERE id = ?
|
|
1336
|
+
""",
|
|
1337
|
+
(session_id,),
|
|
1338
|
+
)
|
|
1339
|
+
|
|
1340
|
+
# 3. Copy nodes
|
|
1341
|
+
await db.execute(
|
|
1342
|
+
"""
|
|
1343
|
+
INSERT OR IGNORE INTO dest.nodes (session_id, id, schema_type, pik_json, data_json, status, action_id, created_at, updated_at)
|
|
1344
|
+
SELECT session_id, id, schema_type, pik_json, data_json, status, action_id, created_at, updated_at
|
|
1345
|
+
FROM nodes
|
|
1346
|
+
WHERE session_id = ?
|
|
1347
|
+
""",
|
|
1348
|
+
(session_id,),
|
|
1349
|
+
)
|
|
1350
|
+
|
|
1351
|
+
# 4. Copy edges
|
|
1352
|
+
await db.execute(
|
|
1353
|
+
"""
|
|
1354
|
+
INSERT OR IGNORE INTO dest.edges (session_id, source_id, target_id, relation_type, action_id, created_at, updated_at)
|
|
1355
|
+
SELECT session_id, source_id, target_id, relation_type, action_id, created_at, updated_at
|
|
1356
|
+
FROM edges
|
|
1357
|
+
WHERE session_id = ?
|
|
1358
|
+
""",
|
|
1359
|
+
(session_id,),
|
|
1360
|
+
)
|
|
1361
|
+
|
|
1362
|
+
# 5. Copy event_log
|
|
1363
|
+
await db.execute(
|
|
1364
|
+
"""
|
|
1365
|
+
INSERT OR IGNORE INTO dest.event_log (id, session_id, timestamp, action_payload, result_payload, human_readable, schema_type, finding_json, closed)
|
|
1366
|
+
SELECT id, session_id, timestamp, action_payload, result_payload, human_readable, schema_type, finding_json, closed
|
|
1367
|
+
FROM event_log
|
|
1368
|
+
WHERE session_id = ?
|
|
1369
|
+
""",
|
|
1370
|
+
(session_id,),
|
|
1371
|
+
)
|
|
1372
|
+
|
|
1373
|
+
# 6. Copy notes
|
|
1374
|
+
await db.execute(
|
|
1375
|
+
"""
|
|
1376
|
+
INSERT OR IGNORE INTO dest.notes (scope_type, scope_id, content, updated_at)
|
|
1377
|
+
SELECT scope_type, scope_id, content, updated_at
|
|
1378
|
+
FROM notes
|
|
1379
|
+
WHERE (scope_type = 'session' AND scope_id = ?)
|
|
1380
|
+
OR (scope_type = 'learning' AND scope_id = ?)
|
|
1381
|
+
""",
|
|
1382
|
+
(session_id, session_id),
|
|
1383
|
+
)
|
|
1384
|
+
|
|
1385
|
+
await db.commit()
|
|
1386
|
+
if os.path.exists(dest_db_path):
|
|
1387
|
+
try:
|
|
1388
|
+
os.chmod(dest_db_path, 0o600)
|
|
1389
|
+
except OSError:
|
|
1390
|
+
pass
|
|
1391
|
+
except Exception:
|
|
1392
|
+
await db.rollback()
|
|
1393
|
+
raise
|
|
1394
|
+
finally:
|
|
1395
|
+
try:
|
|
1396
|
+
await db.execute("DETACH DATABASE dest")
|
|
1397
|
+
except Exception:
|
|
1398
|
+
pass
|
|
1399
|
+
|
|
1400
|
+
async def import_session(
|
|
1401
|
+
self, src_db_path: str, target_workspace_id: Optional[str] = None
|
|
1402
|
+
) -> str:
|
|
1403
|
+
"""Import a session from an exported SQLite database into this store.
|
|
1404
|
+
|
|
1405
|
+
If the session already exists, it is overwritten (restored).
|
|
1406
|
+
Returns the imported session ID.
|
|
1407
|
+
"""
|
|
1408
|
+
async with self._get_conn() as db:
|
|
1409
|
+
db.row_factory = aiosqlite.Row
|
|
1410
|
+
await db.execute("ATTACH DATABASE ? AS src", (src_db_path,))
|
|
1411
|
+
try:
|
|
1412
|
+
cursor = await db.execute("SELECT * FROM src.sessions LIMIT 1")
|
|
1413
|
+
src_session = await cursor.fetchone()
|
|
1414
|
+
if not src_session:
|
|
1415
|
+
raise ValueError("No session found in the source database.")
|
|
1416
|
+
|
|
1417
|
+
src_session_id = src_session["id"]
|
|
1418
|
+
src_session_name = src_session["name"]
|
|
1419
|
+
src_session_status = src_session["status"]
|
|
1420
|
+
src_session_created = src_session["created_at"]
|
|
1421
|
+
|
|
1422
|
+
cursor_ws = await db.execute(
|
|
1423
|
+
"SELECT name FROM src.workspaces WHERE id = ?", (src_session["workspace_id"],)
|
|
1424
|
+
)
|
|
1425
|
+
ws_row = await cursor_ws.fetchone()
|
|
1426
|
+
src_workspace_name = ws_row["name"] if ws_row else "Imported Workspace"
|
|
1427
|
+
|
|
1428
|
+
if target_workspace_id:
|
|
1429
|
+
cursor_target_ws = await db.execute(
|
|
1430
|
+
"SELECT id FROM workspaces WHERE id = ?", (target_workspace_id,)
|
|
1431
|
+
)
|
|
1432
|
+
t_ws = await cursor_target_ws.fetchone()
|
|
1433
|
+
if not t_ws:
|
|
1434
|
+
raise ValueError(f"Target workspace ID '{target_workspace_id}' not found.")
|
|
1435
|
+
final_workspace_id = target_workspace_id
|
|
1436
|
+
else:
|
|
1437
|
+
if src_workspace_name.lower() == "learning sandbox":
|
|
1438
|
+
cursor_target_ws = await db.execute(
|
|
1439
|
+
"SELECT id FROM workspaces WHERE LOWER(name) = 'learning sandbox' LIMIT 1"
|
|
1440
|
+
)
|
|
1441
|
+
else:
|
|
1442
|
+
cursor_target_ws = await db.execute(
|
|
1443
|
+
"SELECT id FROM workspaces WHERE LOWER(name) = ? AND status != 'SYSTEM' LIMIT 1",
|
|
1444
|
+
(src_workspace_name.lower(),),
|
|
1445
|
+
)
|
|
1446
|
+
t_ws = await cursor_target_ws.fetchone()
|
|
1447
|
+
if t_ws:
|
|
1448
|
+
final_workspace_id = t_ws["id"]
|
|
1449
|
+
else:
|
|
1450
|
+
import uuid
|
|
1451
|
+
|
|
1452
|
+
final_workspace_id = str(uuid.uuid4())
|
|
1453
|
+
await db.execute(
|
|
1454
|
+
"INSERT INTO workspaces (id, name, status) VALUES (?, ?, 'ACTIVE')",
|
|
1455
|
+
(final_workspace_id, src_workspace_name),
|
|
1456
|
+
)
|
|
1457
|
+
|
|
1458
|
+
# Check if the session already exists by ID in our database
|
|
1459
|
+
cursor_existing_sess = await db.execute(
|
|
1460
|
+
"SELECT id, name, workspace_id FROM sessions WHERE id = ?", (src_session_id,)
|
|
1461
|
+
)
|
|
1462
|
+
existing_sess = await cursor_existing_sess.fetchone()
|
|
1463
|
+
|
|
1464
|
+
if existing_sess:
|
|
1465
|
+
# Clean up existing session data first to overwrite/restore it
|
|
1466
|
+
await db.execute("DELETE FROM sessions WHERE id = ?", (src_session_id,))
|
|
1467
|
+
# Explicit cleanup (cascades should handle this, but just to be sure)
|
|
1468
|
+
await db.execute("DELETE FROM nodes WHERE session_id = ?", (src_session_id,))
|
|
1469
|
+
await db.execute("DELETE FROM edges WHERE session_id = ?", (src_session_id,))
|
|
1470
|
+
await db.execute(
|
|
1471
|
+
"DELETE FROM event_log WHERE session_id = ?", (src_session_id,)
|
|
1472
|
+
)
|
|
1473
|
+
|
|
1474
|
+
# Handle name collision with a DIFFERENT session in the target workspace
|
|
1475
|
+
final_session_name = src_session_name
|
|
1476
|
+
collision_idx = 1
|
|
1477
|
+
while True:
|
|
1478
|
+
cursor_sess = await db.execute(
|
|
1479
|
+
"SELECT id FROM sessions WHERE workspace_id = ? AND LOWER(name) = ? AND id != ? LIMIT 1",
|
|
1480
|
+
(final_workspace_id, final_session_name.lower(), src_session_id),
|
|
1481
|
+
)
|
|
1482
|
+
s_row = await cursor_sess.fetchone()
|
|
1483
|
+
if not s_row:
|
|
1484
|
+
break
|
|
1485
|
+
final_session_name = f"{src_session_name} (Imported {collision_idx})"
|
|
1486
|
+
collision_idx += 1
|
|
1487
|
+
|
|
1488
|
+
await db.execute(
|
|
1489
|
+
"INSERT INTO sessions (id, workspace_id, name, status, created_at) VALUES (?, ?, ?, ?, ?)",
|
|
1490
|
+
(
|
|
1491
|
+
src_session_id,
|
|
1492
|
+
final_workspace_id,
|
|
1493
|
+
final_session_name,
|
|
1494
|
+
src_session_status,
|
|
1495
|
+
src_session_created,
|
|
1496
|
+
),
|
|
1497
|
+
)
|
|
1498
|
+
|
|
1499
|
+
cursor_nodes = await db.execute(
|
|
1500
|
+
"SELECT * FROM src.nodes WHERE session_id = ?", (src_session_id,)
|
|
1501
|
+
)
|
|
1502
|
+
nodes = await cursor_nodes.fetchall()
|
|
1503
|
+
nodes_to_insert = []
|
|
1504
|
+
for n in nodes:
|
|
1505
|
+
schema_type = n["schema_type"]
|
|
1506
|
+
if (
|
|
1507
|
+
not schema_type
|
|
1508
|
+
or not re.match(r"^[a-zA-Z0-9_.]+$", schema_type)
|
|
1509
|
+
or len(schema_type) > 64
|
|
1510
|
+
):
|
|
1511
|
+
raise ValueError(f"Invalid schema_type '{schema_type}' in imported node.")
|
|
1512
|
+
try:
|
|
1513
|
+
pik_val = json.loads(n["pik_json"])
|
|
1514
|
+
data_val = json.loads(n["data_json"])
|
|
1515
|
+
if not isinstance(pik_val, dict) or not isinstance(data_val, dict):
|
|
1516
|
+
raise ValueError
|
|
1517
|
+
except Exception:
|
|
1518
|
+
raise ValueError(
|
|
1519
|
+
f"Corrupt JSON payload in imported node {n['id']}."
|
|
1520
|
+
) from None
|
|
1521
|
+
|
|
1522
|
+
nodes_to_insert.append(
|
|
1523
|
+
(
|
|
1524
|
+
src_session_id,
|
|
1525
|
+
n["id"],
|
|
1526
|
+
schema_type,
|
|
1527
|
+
json.dumps(pik_val),
|
|
1528
|
+
json.dumps(data_val),
|
|
1529
|
+
n["status"],
|
|
1530
|
+
n["action_id"] if "action_id" in n.keys() else None,
|
|
1531
|
+
n["created_at"] if "created_at" in n.keys() else n["updated_at"],
|
|
1532
|
+
n["updated_at"],
|
|
1533
|
+
)
|
|
1534
|
+
)
|
|
1535
|
+
|
|
1536
|
+
if nodes_to_insert:
|
|
1537
|
+
await db.executemany(
|
|
1538
|
+
"""INSERT INTO nodes (session_id, id, schema_type, pik_json, data_json, status, action_id, created_at, updated_at)
|
|
1539
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
|
1540
|
+
nodes_to_insert,
|
|
1541
|
+
)
|
|
1542
|
+
|
|
1543
|
+
cursor_edges = await db.execute(
|
|
1544
|
+
"SELECT * FROM src.edges WHERE session_id = ?", (src_session_id,)
|
|
1545
|
+
)
|
|
1546
|
+
edges = await cursor_edges.fetchall()
|
|
1547
|
+
if edges:
|
|
1548
|
+
edges_to_insert = [
|
|
1549
|
+
(
|
|
1550
|
+
src_session_id,
|
|
1551
|
+
e["source_id"],
|
|
1552
|
+
e["target_id"],
|
|
1553
|
+
e["relation_type"],
|
|
1554
|
+
e["action_id"] if "action_id" in e.keys() else None,
|
|
1555
|
+
e["created_at"] if "created_at" in e.keys() else None,
|
|
1556
|
+
e["updated_at"] if "updated_at" in e.keys() else None,
|
|
1557
|
+
)
|
|
1558
|
+
for e in edges
|
|
1559
|
+
]
|
|
1560
|
+
await db.executemany(
|
|
1561
|
+
"""INSERT INTO edges (session_id, source_id, target_id, relation_type, action_id, created_at, updated_at)
|
|
1562
|
+
VALUES (?, ?, ?, ?, ?, COALESCE(?, CURRENT_TIMESTAMP), COALESCE(?, CURRENT_TIMESTAMP))""",
|
|
1563
|
+
edges_to_insert,
|
|
1564
|
+
)
|
|
1565
|
+
|
|
1566
|
+
cursor_events = await db.execute(
|
|
1567
|
+
"SELECT * FROM src.event_log WHERE session_id = ?", (src_session_id,)
|
|
1568
|
+
)
|
|
1569
|
+
events = await cursor_events.fetchall()
|
|
1570
|
+
if events:
|
|
1571
|
+
events_to_insert = [
|
|
1572
|
+
(
|
|
1573
|
+
src_session_id,
|
|
1574
|
+
ev["timestamp"],
|
|
1575
|
+
ev["action_payload"],
|
|
1576
|
+
ev["result_payload"],
|
|
1577
|
+
ev["human_readable"],
|
|
1578
|
+
ev["schema_type"],
|
|
1579
|
+
ev["finding_json"],
|
|
1580
|
+
ev["closed"],
|
|
1581
|
+
)
|
|
1582
|
+
for ev in events
|
|
1583
|
+
]
|
|
1584
|
+
await db.executemany(
|
|
1585
|
+
"INSERT INTO event_log (session_id, timestamp, action_payload, result_payload, human_readable, schema_type, finding_json, closed) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
1586
|
+
events_to_insert,
|
|
1587
|
+
)
|
|
1588
|
+
|
|
1589
|
+
# Import notes if present in src
|
|
1590
|
+
try:
|
|
1591
|
+
cursor_notes = await db.execute(
|
|
1592
|
+
"SELECT * FROM src.notes WHERE scope_id = ?", (src_session_id,)
|
|
1593
|
+
)
|
|
1594
|
+
notes_rows = await cursor_notes.fetchall()
|
|
1595
|
+
if notes_rows:
|
|
1596
|
+
notes_to_insert = [
|
|
1597
|
+
(n["scope_type"], src_session_id, n["content"]) for n in notes_rows
|
|
1598
|
+
]
|
|
1599
|
+
await db.executemany(
|
|
1600
|
+
"INSERT OR REPLACE INTO notes (scope_type, scope_id, content) VALUES (?, ?, ?)",
|
|
1601
|
+
notes_to_insert,
|
|
1602
|
+
)
|
|
1603
|
+
except Exception:
|
|
1604
|
+
pass
|
|
1605
|
+
|
|
1606
|
+
await db.commit()
|
|
1607
|
+
return src_session_id
|
|
1608
|
+
except Exception:
|
|
1609
|
+
await db.rollback()
|
|
1610
|
+
raise
|
|
1611
|
+
finally:
|
|
1612
|
+
try:
|
|
1613
|
+
await db.execute("DETACH DATABASE src")
|
|
1614
|
+
except Exception:
|
|
1615
|
+
pass
|