tortoise-graph 0.2.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.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,913 @@
1
+ """Projection — fold the event log into the current graph.
2
+
3
+ The log is the source of truth; a projection is a derived, rebuildable view.
4
+ `_apply_one` is the single source of fold semantics, shared by the pure `fold`
5
+ (batch) and every incremental backend, so an incrementally-updated projection and
6
+ `fold(read_all())` can never diverge.
7
+
8
+ Backends behind the `Projection` protocol:
9
+ - InMemoryProjection — dict of points (statements AND operators).
10
+ - FalkorProjection — FalkorDB (Docker/server by default, embedded via path=);
11
+ same openCypher graph so portable between modes
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ import os
17
+ from datetime import datetime, timezone
18
+ from typing import Protocol, runtime_checkable
19
+
20
+ # P0 guard (#99): bulk graph-wipe classifier. Restored here in #49 Phase 2 —
21
+ # the guard was lost from this (live) module during the v3.0 ontology rewrite
22
+ # (0f9e6a2) and only survived in the legacy standalone projection.py, which
23
+ # Phase 2 deletes. This is the ACTIVE wipe-protection: it must live in the
24
+ # module the SDK actually imports.
25
+ # A query is a bulk wipe when it contains DETACH DELETE but has NO property map
26
+ # ({...} — e.g. MATCH (n:Label {id:$id})) and NO real WHERE clause.
27
+ # A WHERE clause is "real" only if it references a property (n.xxx) or a
28
+ # parameter ($id) or CONTAINS/IN — tautologies (WHERE true, WHERE 1=1) don't count.
29
+ _WHERE_REAL_RE = re.compile(
30
+ r"\b[a-zA-Z_][a-zA-Z0-9_]*\.[a-zA-Z_][a-zA-Z0-9_]*|\$[a-zA-Z_]|CONTAINS|IN\s*\(",
31
+ re.IGNORECASE,
32
+ )
33
+
34
+
35
+ def _is_bulk_wipe(cypher: str) -> bool:
36
+ up = cypher.upper()
37
+ if "DETACH" not in up or "DELETE" not in up:
38
+ return False
39
+ # Property map in MATCH => targeted (e.g. {id:$id}, {team_id:$id})
40
+ if "{" in cypher:
41
+ return False
42
+ # Real WHERE clause (property/param/CONTAINS/IN reference) => targeted
43
+ m = re.search(r"WHERE\s+(.+) ", cypher + " ", re.IGNORECASE)
44
+ if m and _WHERE_REAL_RE.search(m.group(1)):
45
+ return False
46
+ return True
47
+
48
+
49
+ class _GuardedGraph:
50
+ """Wrapper around the FalkorDB Graph handle that guards bulk graph-wipe queries.
51
+
52
+ The SDK calls proj.g.query() (raw handle) throughout — the guard must wrap
53
+ self.g itself, not FalkorProjection.query(). Restored in #49 Phase 2 after
54
+ the v3.0 rewrite (0f9e6a2) dropped it from this live module.
55
+
56
+ Intercepts bulk DETACH DELETE (no property map, no real WHERE) and asserts
57
+ the graph is a test graph before allowing execution. Targeted deletes
58
+ (MATCH (n:Label {id:$id}) ...) pass through unchanged.
59
+ """
60
+
61
+ __slots__ = ("_g", "_proj")
62
+
63
+ def __init__(self, g, projection):
64
+ self._g = g
65
+ self._proj = projection
66
+
67
+ def query(self, cypher: str, params=None, timeout=None):
68
+ if _is_bulk_wipe(cypher) and not getattr(self._proj, "_skip_guard", False):
69
+ self._proj._assert_test_graph(
70
+ "REFUSING to run bulk DETACH DELETE on non-test graph"
71
+ )
72
+ return self._g.query(cypher, params=params, timeout=timeout)
73
+
74
+ def __getattr__(self, name):
75
+ return getattr(self._g, name)
76
+
77
+ from tortoise.config import RELATIVE_PATH_ERROR
78
+
79
+ # ── Mixins ────────────────────────────────────────────────────────────────
80
+ from tortoise.projection.entities import _EntityHandlers
81
+ from tortoise.projection.edges import _EdgeHandlers
82
+ from tortoise.projection.grounding import _GroundingMixin
83
+ from tortoise.projection.propagation import _PropagationMixin
84
+
85
+ # #244: Event FTS index migration (subject-only → subject+name) is tracked by a
86
+ # persisted DB marker (Meta node 'event_fts_v2'), not a process-local flag — a
87
+ # module-level bool resets every restart and would drop+recreate the index on
88
+ # every boot (churn + crash window on server FalkorDB). See _ensure_indexes.
89
+
90
+ # ── Module-level helpers ──────────────────────────────────────────────────
91
+
92
+
93
+ def _now_iso() -> str:
94
+ return datetime.now(timezone.utc).isoformat()
95
+
96
+
97
+ def _norm(ev: dict) -> dict:
98
+ """Normalize event shape — tolerates API (flat) and script (nested point)."""
99
+ if ev.get("point"):
100
+ return {**ev, **ev["point"]}
101
+ return ev
102
+
103
+
104
+ def _apply_one(points: dict[str, dict], ev: dict) -> None:
105
+ ev = _norm(ev)
106
+ t = ev["type"]
107
+ if t in ("PointAdded", "OperatorAdded"):
108
+ p = ev["point"]
109
+ # Phase 1 stop-writes: strip context from v2+ events (#49)
110
+ if ev.get("projection_version", 0) >= 2:
111
+ p.pop("context", None)
112
+ points[p["id"]] = p
113
+ # Flatten speaker from point's provenance into node data
114
+ prov = p.get("provenance", {})
115
+ if prov.get("speaker"):
116
+ p["speaker"] = prov["speaker"]
117
+ elif t == "PointRevised":
118
+ p = points.get(ev["id"])
119
+ if p:
120
+ if ev.get("new_content") is not None:
121
+ p["content"] = ev["new_content"]
122
+ # Phase 1: discard new_context for v2+ events (#49)
123
+ if ev.get("new_context") is not None and ev.get("projection_version", 0) < 2:
124
+ p["context"] = ev["new_context"]
125
+ elif t == "PointRetracted":
126
+ points.pop(ev["id"], None)
127
+ elif t == "PointsMerged":
128
+ for mid in ev.get("merge_ids", []):
129
+ points.pop(mid, None)
130
+ # IngestStarted: no graph effect
131
+
132
+
133
+ def fold(events: list[dict]) -> dict[str, dict]:
134
+ points: dict[str, dict] = {}
135
+ for ev in events:
136
+ _apply_one(points, ev)
137
+ return points
138
+
139
+
140
+ def split(points: dict[str, dict]) -> tuple[list[dict], list[dict]]:
141
+ """Partition into (statement points, operator points)."""
142
+ statements, operators = [], []
143
+ for p in points.values():
144
+ (operators if p.get("operator") else statements).append(p)
145
+ return statements, operators
146
+
147
+
148
+ # ── Protocol + InMemory ───────────────────────────────────────────────────
149
+
150
+
151
+ @runtime_checkable
152
+ class Projection(Protocol):
153
+ def apply(self, event: dict) -> None: ...
154
+ def rebuild(self, log) -> None: ...
155
+
156
+
157
+ class InMemoryProjection:
158
+ def __init__(self):
159
+ self.points: dict[str, dict] = {}
160
+
161
+ def apply(self, event: dict) -> None:
162
+ _apply_one(self.points, event)
163
+
164
+ def rebuild(self, log) -> None:
165
+ self.points = fold(log.read_all())
166
+
167
+
168
+ _SUPPORTED_URI_SCHEMES = ("docker", "redis", "rediss")
169
+
170
+
171
+ def _validate_uri_scheme(scheme: str) -> str:
172
+ """Accept docker:// (local) and redis:// / rediss:// (FalkorDB Cloud) URIs.
173
+
174
+ Raises ValueError for anything else, mirroring the historical docker://-only
175
+ contract while making managed-instance URIs first-class.
176
+ """
177
+ if scheme not in _SUPPORTED_URI_SCHEMES:
178
+ raise ValueError(
179
+ f"Unsupported scheme: {scheme} "
180
+ f"(expected docker://, redis://, or rediss://). "
181
+ f"Example: docker://:password@localhost:6379/tortoise"
182
+ )
183
+ return scheme
184
+
185
+
186
+ # ── FalkorProjection ──────────────────────────────────────────────────────
187
+
188
+
189
+ class FalkorProjection(
190
+ _EntityHandlers,
191
+ _EdgeHandlers,
192
+ _GroundingMixin,
193
+ _PropagationMixin,
194
+ ):
195
+ """FalkorDB-backed projection. Supports Docker/server (default) and embedded modes.
196
+
197
+ Embedded: FalkorProjection(path='/tmp/tortoise.db')
198
+ Docker: FalkorProjection(host='localhost', port=16379, password='...')
199
+ URI: FalkorProjection.from_uri('docker://:pass@host:6379/graph')
200
+
201
+ Same API regardless of backend — constructor swap is the only difference.
202
+ """
203
+
204
+ def __init__(self, path: str | None = None, *,
205
+ host: str | None = None,
206
+ port: int = 16379,
207
+ username: str | None = None,
208
+ password: str | None = None,
209
+ graph_name: str = "tortoise",
210
+ ssl: bool = False,
211
+ allow_nonstandard_path: bool = False,
212
+ skip_health_check: bool = False):
213
+
214
+ # No-arg construction -> canonical embedded path (plan Task 9: graph-
215
+ # scripts migrated from FalkorProjection('tortoise.db') to no-arg,
216
+ # which must resolve to the canonical TORTOISE_DB_PATH).
217
+ if path is None and host is None:
218
+ from tortoise.config import resolve_db_path
219
+ path = resolve_db_path()
220
+
221
+ if path is not None:
222
+ # Hard-reject relative paths (plan Task 7, issue #176): a relative
223
+ # path like 'tortoise.db' resolves per-CWD and silently creates a
224
+ # per-directory redislite server (Category-3 leak). Relative is
225
+ # ALWAYS rejected — the escape hatch only permits absolute
226
+ # non-canonical paths. Env TORTOISE_ALLOW_NONSTANDARD_PATH=1
227
+ # enables the same escape hatch without the kwarg.
228
+ if not allow_nonstandard_path and \
229
+ os.environ.get("TORTOISE_ALLOW_NONSTANDARD_PATH") == "1":
230
+ allow_nonstandard_path = True
231
+ if not os.path.isabs(path) and not path.startswith("~"):
232
+ raise ValueError(RELATIVE_PATH_ERROR.format(path=path))
233
+ if path.startswith("~") and not allow_nonstandard_path:
234
+ # tilde is only valid if expanded to absolute via env;
235
+ # unexpanded it is relative-like -> reject with hint
236
+ raise ValueError(RELATIVE_PATH_ERROR.format(path=path))
237
+
238
+ # Embedded mode (opt-in via path=). Use redislite's FalkorDB client —
239
+ # the plain falkordb.FalkorDB treats a positional path arg as a HOST
240
+ # (IDNA crash: redis tries to resolve the file path as a hostname, #82).
241
+ from redislite.falkordb_client import FalkorDB # lazy: keep import optional
242
+ self.db = FalkorDB(path)
243
+ elif host is not None:
244
+ # Docker FalkorDB
245
+ from falkordb import FalkorDB # ponytail: lazy import, only needed for Docker mode
246
+ self.db = FalkorDB(host=host, port=port, username=username, password=password,
247
+ socket_connect_timeout=5, socket_timeout=10, ssl=ssl)
248
+ else:
249
+ raise ValueError("Either path or host must be provided")
250
+
251
+ self.g = _GuardedGraph(self.db.select_graph(graph_name), self)
252
+ self.graph_name = graph_name
253
+ self._graph_name = graph_name
254
+ self._skip_guard = False
255
+ self._is_embedded = (path is not None)
256
+ self._path = path
257
+ # Ops safety residual (#428): auto health check on open + transparent
258
+ # corruption recovery. Embedded DBs rebuild from their adjacent JSONL
259
+ # event log when lost/corrupt; production (FLY_APP_NAME) and server
260
+ # mode fail loud instead. Runs BEFORE _ensure_indexes so a corrupt
261
+ # DB is recovered before index creation. skip_health_check is the
262
+ # escape hatch for the `tortoise rebuild` CLI itself (it IS the
263
+ # recovery tool — gating it on a healthy DB would be circular).
264
+ if not skip_health_check:
265
+ self._auto_health_recover()
266
+ self._falkordb_version = self._get_falkordb_version()
267
+ if self._falkordb_version is not None and self._falkordb_version[0] < 4:
268
+ import logging
269
+ logging.getLogger(__name__).warning(
270
+ "FalkorDB version %s is below minimum 4.x. FTS and vector indexes will be skipped.",
271
+ '.'.join(map(str, self._falkordb_version)))
272
+ elif self._falkordb_version is None:
273
+ import logging
274
+ logging.getLogger(__name__).warning(
275
+ "Could not determine FalkorDB version. FTS and vector indexes may fail.")
276
+ self._ensure_indexes()
277
+
278
+ # Lifecycle hardening (plan Task 4):
279
+ # - _closed flag for idempotent close()
280
+ # - weakref.finalize so GC cleans up without explicit close
281
+ # - atexit so normal process exit never orphans the server
282
+ # - NO per-instance signal handlers (atexit suffices; avoids leaks)
283
+ import atexit as _atexit
284
+ import weakref as _weakref
285
+ self._closed = False
286
+ self._finalizer = _weakref.finalize(self, self.close)
287
+ _atexit.register(self.close)
288
+
289
+ # ── Ops safety (#428): health check + transparent recovery ────────────
290
+
291
+ def _probe_ok(self) -> bool:
292
+ """Cheap connectivity probe — does the graph answer queries?"""
293
+ try:
294
+ self.g.query("MATCH (n) RETURN count(n) LIMIT 1")
295
+ return True
296
+ except Exception:
297
+ return False
298
+
299
+ def _find_local_jsonl_dir(self) -> str | None:
300
+ """Adjacent JSONL event-log dir (same directory as the embedded DB).
301
+
302
+ Recovery only ever rebuilds from a log that lives next to the DB
303
+ file — a global ~/.tortoise scan could rebuild a dev DB from an
304
+ unrelated production log. Returns None when no *.jsonl is adjacent.
305
+ """
306
+ if not self._path:
307
+ return None
308
+ try:
309
+ db_dir = os.path.dirname(
310
+ os.path.abspath(os.path.expanduser(self._path)))
311
+ if any(f.endswith(".jsonl") for f in os.listdir(db_dir)):
312
+ return db_dir
313
+ except OSError:
314
+ return None
315
+ return None
316
+
317
+ def _auto_health_recover(self) -> None:
318
+ """Health check on open + transparent JSONL recovery (embedded only).
319
+
320
+ The event log is the source of truth; the projection a derived view.
321
+ Two corruption modes are caught:
322
+ 1. Unresponsive graph (open succeeded, queries fail).
323
+ 2. Lost graph — 0 nodes while the adjacent JSONL log has events
324
+ (redislite starts fresh when its RDB is corrupt, interrupted
325
+ restore, manual deletion). Rebuilt via recover_from_log.
326
+
327
+ Recovery is embedded-only and NEVER runs when FLY_APP_NAME is set
328
+ (production): there a silent rebuild could mask an infra failure and
329
+ a remote DB is never rebuilt from a local log. Server/URI mode and
330
+ production fail loud with an actionable error instead.
331
+ """
332
+ import logging
333
+ logger = logging.getLogger(__name__)
334
+ is_prod = bool(os.environ.get("FLY_APP_NAME"))
335
+
336
+ if not self._probe_ok():
337
+ if is_prod or not self._is_embedded:
338
+ raise RuntimeError(
339
+ "DB health check failed on open (server/production mode). "
340
+ "Recover manually: python -m tortoise rebuild --dir "
341
+ "<jsonl-dir> --db <db> — see "
342
+ "operations/skills/tortoise-rebuild/SKILL.md")
343
+ events_dir = self._find_local_jsonl_dir()
344
+ if not events_dir:
345
+ raise RuntimeError(
346
+ f"DB health check failed on open and no adjacent JSONL "
347
+ f"event log was found for recovery ({self._path!r}). "
348
+ f"Restore from backup or rebuild manually — see "
349
+ f"operations/skills/tortoise-rebuild/SKILL.md")
350
+ self._recover_or_raise(events_dir)
351
+ logger.warning("auto-recovered embedded DB from %s", events_dir)
352
+ return
353
+
354
+ # Probe passed. Embedded dev mode: check the lost-graph divergence
355
+ # (0 nodes + non-empty adjacent log). Server/prod skips — a remote
356
+ # graph is never rebuilt from a local log.
357
+ if self._is_embedded and not is_prod:
358
+ events_dir = self._find_local_jsonl_dir()
359
+ if events_dir:
360
+ from tortoise.consistency import recover_from_log
361
+ result = recover_from_log(events_dir, self)
362
+ if result.get("recovered"):
363
+ logger.warning(
364
+ "auto-recovered empty embedded DB from %s (%s events)",
365
+ events_dir, result.get("log_points"))
366
+ elif result.get("reason"):
367
+ # Lost-graph case but recovery declined (ambiguous/unreadable
368
+ # log) — warn loudly instead of silently continuing with an
369
+ # empty DB (ops safety #428: no silent data loss).
370
+ logger.warning(
371
+ "empty embedded DB not auto-recovered: %s",
372
+ result.get("reason"))
373
+
374
+ def _recover_or_raise(self, events_dir: str) -> None:
375
+ """Run recover_from_log and fail loud if it did not recover."""
376
+ from tortoise.consistency import recover_from_log
377
+ result = recover_from_log(events_dir, self)
378
+ if not result.get("recovered"):
379
+ raise RuntimeError(
380
+ f"DB health check failed and recovery did not complete: "
381
+ f"{result.get('reason')}. "
382
+ f"See operations/skills/tortoise-rebuild/SKILL.md")
383
+
384
+ @classmethod
385
+ def from_uri(cls, uri: str, graph_name: str | None = None) -> "FalkorProjection":
386
+ """Parse a connection URI into a projection.
387
+
388
+ Supported schemes (all treated as docker://):
389
+ docker://:password@host:port/graph_name — canonical local form
390
+ redis:// or rediss:// — FalkorDB Cloud / managed
391
+ instances use the redis
392
+ scheme; accept as aliases.
393
+
394
+ graph_name overrides the URI path (multi-tenant isolation, #7886) —
395
+ each tenant SDK selects its own graph instead of the URI default.
396
+
397
+ Unsupported schemes raise ValueError with an actionable message.
398
+ """
399
+ from urllib.parse import urlparse
400
+ parsed = urlparse(uri)
401
+ _validate_uri_scheme(parsed.scheme)
402
+ username = parsed.username or None
403
+ password = parsed.password or None
404
+ if graph_name is None:
405
+ graph_name = parsed.path.lstrip('/') or "tortoise"
406
+ return cls(host=parsed.hostname or "localhost",
407
+ port=parsed.port or 16379,
408
+ username=username,
409
+ password=password,
410
+ graph_name=graph_name,
411
+ ssl=(parsed.scheme == "rediss"))
412
+
413
+ def _norm(self, ev: dict) -> dict:
414
+ """Normalize event shape — tolerates API (flat) and script (nested point)."""
415
+ if ev.get("point"):
416
+ # Script format: id lives inside point
417
+ return {**ev, **ev["point"]}
418
+ return ev
419
+
420
+ def apply(self, event: dict) -> None:
421
+ ev = self._norm(event)
422
+ t = ev["type"]
423
+ if t in ("PointAdded", "OperatorAdded"):
424
+ p = ev["point"]
425
+ # Phase 1 stop-writes: strip context from v2+ events (#49)
426
+ if ev.get("projection_version", 0) >= 2:
427
+ p.pop("context", None)
428
+ self._upsert(p)
429
+ elif t == "PointRevised":
430
+ # Phase 1: discard new_context for v2+ events (#49)
431
+ if ev.get("projection_version", 0) >= 2:
432
+ ev.pop("new_context", None)
433
+ self._revise_point(ev, set_updated_at=True)
434
+ elif t == "PointRetracted":
435
+ self._delete(ev["id"])
436
+ elif t == "PointsMerged":
437
+ for mid in event.get("merge_ids", []):
438
+ self._delete(mid)
439
+ elif t == "EventRecorded":
440
+ self._upsert_event(ev)
441
+ elif t == "SubjectAdded":
442
+ self._upsert_subject(ev)
443
+ elif t == "ObjectRegistered":
444
+ self._upsert_object(ev)
445
+ elif t == "DocumentCreated":
446
+ self._upsert_document(ev)
447
+ elif t == "SourceCreated":
448
+ self._upsert_source(ev)
449
+
450
+ def rebuild(self, log) -> None:
451
+ self.g.query("MATCH (n) DETACH DELETE n")
452
+ for ev in log.read_all():
453
+ self.apply(ev)
454
+
455
+ def rebuild_all(self, log_dir: str) -> dict:
456
+ """Rebuild from all .jsonl files in a directory. Returns counts.
457
+
458
+ Two-pass: creates all Point nodes first (pass 1), then operator edges
459
+ and all other event types second (pass 2), so cross-file operator→Point
460
+ references always resolve regardless of filename sort order.
461
+
462
+ GAP-19: Full event-type coverage — replays all EventRecorded, SubjectAdded,
463
+ ObjectRegistered, DocumentCreated, SourceCreated, ConfidenceChanged,
464
+ PointRevised events, not just PointAdded/OperatorAdded/PointRetracted/
465
+ PointsMerged.
466
+
467
+ #330 parity guarantee: for logs where SourceCreated precedes the
468
+ PointAdded events that extract from that source (the canonical ingest
469
+ order), rebuild produces the SAME Point node properties + edges as
470
+ replaying through apply(). A reversed order (extractedFrom-bearing
471
+ point before its SourceCreated) can diverge Source node version/id
472
+ properties — known, documented limitation.
473
+ """
474
+ import os
475
+ from tortoise.log import EventLog
476
+ self.g.query("MATCH (n) DETACH DELETE n")
477
+
478
+ # Collect all events from all files
479
+ events = []
480
+ for fname in sorted(os.listdir(log_dir)):
481
+ if fname.endswith('.jsonl'):
482
+ events.extend(EventLog(os.path.join(log_dir, fname)).read_all())
483
+
484
+ # Pass 1: create all Point/Operator nodes (skip edges) + non-edge events
485
+ # Pass 1a: create all Point/Operator nodes first
486
+ # (skip edges), so cross-file PointRevised always has a node to revise (#21).
487
+ for ev in events:
488
+ t = ev["type"]
489
+ if t in ("PointAdded", "OperatorAdded"):
490
+ p = ev["point"]
491
+ # Phase 1 stop-writes: strip context from v2+ events (#49)
492
+ # (identical to apply() — parity between rebuild and apply)
493
+ if ev.get("projection_version", 0) >= 2:
494
+ p.pop("context", None)
495
+ # Property parity with apply()/apply_one (#330): the shared
496
+ # helper writes ALL node properties incl. authoredBy,
497
+ # embedding, validFrom/To, extractedFrom, provenanceSource.
498
+ self._upsert_point_props(p)
499
+
500
+ # Pass 1b: apply revisions + other non-edge events AFTER all nodes exist
501
+ for ev in events:
502
+ t = ev["type"]
503
+ if t in ("PointAdded", "OperatorAdded"):
504
+ continue # already handled in pass 1a
505
+ elif t == "PointRetracted":
506
+ self._delete(ev.get("id") or ev["event_id"])
507
+ elif t == "PointsMerged":
508
+ for mid in ev.get("merge_ids", []):
509
+ self._delete(mid)
510
+ elif t == "PointRevised":
511
+ # Phase 1: discard new_context for v2+ events (#49)
512
+ if ev.get("projection_version", 0) >= 2:
513
+ ev.pop("new_context", None)
514
+ # set_updated_at parity with apply() (#330)
515
+ self._revise_point(ev, set_updated_at=True)
516
+ elif t == "EventRecorded":
517
+ self._upsert_event(ev)
518
+ elif t == "SubjectAdded":
519
+ self._upsert_subject(ev)
520
+ elif t == "ObjectRegistered":
521
+ self._upsert_object(ev)
522
+ elif t == "DocumentCreated":
523
+ self._upsert_document(ev)
524
+ elif t == "SourceCreated":
525
+ # #330 parity with apply(): SourceCreated was dropped by rebuild.
526
+ self._upsert_source(ev)
527
+ # ConfidenceChanged: no graph effect (audit-only event)
528
+
529
+ # Pass 2: create edges for all operators + provenance/entity wiring
530
+ # (shared _upsert_point_edges — single source of truth with apply, #330).
531
+ for ev in events:
532
+ if ev["type"] in ("PointAdded", "OperatorAdded"):
533
+ p = ev["point"]
534
+ if ev.get("projection_version", 0) >= 2:
535
+ p.pop("context", None)
536
+ self._upsert_point_edges(p)
537
+
538
+ node_count = self.g.query(
539
+ "MATCH (n:Point) RETURN count(n)"
540
+ ).result_set[0][0]
541
+ edge_count = self.g.query(
542
+ "MATCH ()-[r]->() RETURN count(r)"
543
+ ).result_set[0][0]
544
+ return {"events": len(events), "nodes": node_count, "edges": edge_count}
545
+
546
+ def query(self, cypher: str, **params):
547
+ # P0 guard (#99): refuse bulk graph-wipe on non-test graphs.
548
+ # Respect _skip_guard (consistent with _GuardedGraph.query) so a
549
+ # legitimate maintenance bypass works through either call path.
550
+ if _is_bulk_wipe(cypher) and not self._skip_guard:
551
+ self._assert_test_graph(
552
+ f"REFUSING to run bulk DETACH DELETE on non-test graph "
553
+ f"'{self._graph_name}'"
554
+ )
555
+ return self.g.query(cypher, params=params or None)
556
+
557
+ def _assert_test_graph(self, reason: str = "") -> None:
558
+ """Raise RuntimeError if the active graph is not a test graph.
559
+
560
+ Test graphs must start with 'test_' or 'tortoise_test'.
561
+ Embedded mode (path=) is inherently isolated (per-instance temp DB) —
562
+ the guard does NOT apply to it. Only server mode (docker) needs the
563
+ graph-name check, protecting the shared real graph (#99).
564
+ """
565
+ if getattr(self, "_is_embedded", False):
566
+ return
567
+ if not self._graph_name.startswith(("test_", "tortoise_test")):
568
+ msg = (
569
+ f"Graph guard: operation blocked on non-test graph "
570
+ f"'{self._graph_name}'. "
571
+ f"{reason} — destructive bulk ops require a graph name starting "
572
+ f"with 'test_' or 'tortoise_test'."
573
+ ).rstrip()
574
+ raise RuntimeError(msg)
575
+
576
+ def _get_falkordb_version(self):
577
+ """Parse FalkorDB version from db.info().
578
+
579
+ Returns (major, minor, patch) tuple or None if undetermined.
580
+ """
581
+ import re
582
+ try:
583
+ info = self.db.info()
584
+ except Exception:
585
+ return None
586
+
587
+ info_str = info if isinstance(info, str) else str(info)
588
+
589
+ # Module format: module:name=falkordb,ver=40000 (4.0.0)
590
+ m = re.search(r'module:name=(?:falkordb|graph),ver=(\d+)', info_str, re.IGNORECASE)
591
+ if m:
592
+ v = int(m.group(1))
593
+ return (v // 10000, (v // 100) % 100, v % 100)
594
+
595
+ # Server section: falkordb_version:4.0
596
+ try:
597
+ server = self.db.info('server')
598
+ server_str = server if isinstance(server, str) else str(server)
599
+ m = re.search(r'falkordb_version:(\d+)\.(\d+)', server_str)
600
+ if m:
601
+ return (int(m.group(1)), int(m.group(2)), 0)
602
+ except Exception:
603
+ pass
604
+
605
+ return None
606
+
607
+ #: (label, key-property) branches for _resolve_entity — every branch is
608
+ #: backed by a RANGE index created in _ensure_indexes (issue #327).
609
+ #: Event matches by eventId (Event.id == eventId for all current writes;
610
+ #: eventId-only legacy nodes are covered). Source matches by id and/or url
611
+ #: (url-only ingestion stubs from _link_source have no id).
612
+ _RESOLVE_BRANCHES = (
613
+ ("Point", "id"), ("Subject", "id"), ("Object", "id"),
614
+ ("Document", "id"), ("Source", "id"),
615
+ ("Event", "eventId"), ("Source", "url"),
616
+ )
617
+
618
+ def _resolve_entity(self, id_val: str, *, by_id: bool = True,
619
+ by_eventId: bool = False, by_url: bool = False) -> list[dict]:
620
+ """Index-backed entity resolution mirroring the legacy
621
+ `MATCH (n) WHERE n.id=$id OR n.eventId=$id OR n.url=$id` semantics.
622
+
623
+ Returns [{label, key, value, properties}, ...] — one entry per matching
624
+ node, deduped by node identity (a Source with id==url matches two
625
+ branches). Each branch is a labeled lookup on an indexed property, so
626
+ the planner uses Node By Index Scan instead of All Node Scan (#327).
627
+
628
+ ``by_id`` also covers Events via their eventId branch: Event nodes
629
+ always carry id == eventId (both set by _upsert_event; eventId-only
630
+ legacy nodes exist), so matching ``Event {eventId:$id}`` reproduces
631
+ the legacy ``n.id = $id`` lookup for Events exactly.
632
+
633
+ Per-call-site OR-sets (issue #327 scope table):
634
+ - _get_entity: id | eventId | url
635
+ - _update/_delete_entity: id | eventId
636
+ - create_edge source: id | eventId | url ; target: id | eventId
637
+ - create_about_edge source: id ; target: id | eventId
638
+ - create_owned_by / about stub links: id only
639
+ """
640
+ branches = []
641
+ for label, prop in self._RESOLVE_BRANCHES:
642
+ if prop == "id" and not by_id:
643
+ continue
644
+ # Event branch: enabled by by_id (Event.id == eventId invariant)
645
+ # or explicitly by by_eventId.
646
+ if prop == "eventId" and not (by_id or by_eventId):
647
+ continue
648
+ if prop == "url" and not by_url:
649
+ continue
650
+ branches.append((label, prop))
651
+ if not branches:
652
+ return []
653
+ union_q = " UNION ".join(
654
+ f"MATCH (n:{label}) WHERE n.{prop} = $id "
655
+ f"RETURN '{label}' AS label, '{prop}' AS key, n.{prop} AS value, "
656
+ f"properties(n) AS props LIMIT 1"
657
+ for label, prop in branches
658
+ )
659
+ rows = self.g.query(union_q, params={"id": id_val}).result_set
660
+ seen: set[str] = set()
661
+ out: list[dict] = []
662
+ for label, key, value, props in rows:
663
+ ident = props.get("id") or props.get("eventId") or props.get("url")
664
+ if ident in seen:
665
+ continue
666
+ seen.add(ident)
667
+ out.append({"label": label, "key": key, "value": value,
668
+ "properties": dict(props)})
669
+ # Defense-in-depth (issue #327 security review): consumers interpolate
670
+ # label/key into Cypher patterns. Fail loudly here if this producer ever
671
+ # returns anything other than the constant-tuple values — a future
672
+ # dynamic-label branch must not become query-text injection downstream.
673
+ allowed_labels = {lbl for lbl, _ in self._RESOLVE_BRANCHES}
674
+ for r in out:
675
+ if r["label"] not in allowed_labels or r["key"] not in {"id", "eventId", "url"}:
676
+ raise RuntimeError(
677
+ f"_resolve_entity produced unsafe label/key: "
678
+ f"{r['label']!r}/{r['key']!r} (contract: constant tuple only)")
679
+ return out
680
+
681
+ def _ensure_indexes(self) -> None:
682
+ """Create indexes on frequently-filtered Point properties.
683
+
684
+ Wraps CREATE INDEX in try/except because FalkorDB raises
685
+ "Attribute 'X' is already indexed" rather than silently no-opping.
686
+ On subsequent startups, each CREATE INDEX errors immediately
687
+ (O(1) check), so there is no startup penalty on large graphs.
688
+
689
+ FTS and vector indexes are gated on FalkorDB >= 4.x.
690
+ """
691
+ # ── Range indexes (always safe, pre-4.x compatible) ──
692
+ for prop in ("id", "pointKind", "content_hash", "is_operator"):
693
+ try:
694
+ self.g.query(f"CREATE INDEX FOR (n:Point) ON (n.{prop})")
695
+ except Exception as e:
696
+ msg = str(e).lower()
697
+ if "already indexed" in msg or "already exists" in msg:
698
+ pass # expected — index exists from prior startup
699
+ else:
700
+ import logging
701
+ logging.getLogger(__name__).error(
702
+ "Failed to create index on n.%s: %s", prop, e)
703
+
704
+ # ── Document range indexes (#125 — structural queries filter by kind) ──
705
+ for prop in ("id", "documentKind"):
706
+ try:
707
+ self.g.query(f"CREATE INDEX FOR (n:Document) ON (n.{prop})")
708
+ except Exception as e:
709
+ msg = str(e).lower()
710
+ if "already indexed" in msg or "already exists" in msg:
711
+ pass
712
+ else:
713
+ import logging
714
+ logging.getLogger(__name__).error(
715
+ "Failed to create index on Document.%s: %s", prop, e)
716
+
717
+ # ── Range indexes on canonical entity keys (issue #327) ──
718
+ # Point/Document are created above; these enable index-backed
719
+ # _resolve_entity lookups and faster name/url/eventId-keyed MERGE
720
+ # upserts. Deliberately NO status/op_type/kind-field indexes — a
721
+ # measured 3.15x write slowdown on Point upserts with status/op_type
722
+ # outweighs the batch-read benefit (see issue #522).
723
+ for label, props in (("Subject", ("id", "name")),
724
+ ("Object", ("id", "name")),
725
+ ("Event", ("eventId",)),
726
+ ("Source", ("id", "url"))):
727
+ for prop in props:
728
+ try:
729
+ self.g.query(f"CREATE INDEX FOR (n:{label}) ON (n.{prop})")
730
+ except Exception as e:
731
+ msg = str(e).lower()
732
+ if "already indexed" in msg or "already exists" in msg:
733
+ pass
734
+ else:
735
+ import logging
736
+ logging.getLogger(__name__).error(
737
+ "Failed to create index on %s.%s: %s", label, prop, e)
738
+
739
+ # ── Full-text & vector indexes require FalkorDB 4.x+ (#7779) ──
740
+ _ver = getattr(self, '_falkordb_version', None)
741
+ if _ver is None or _ver[0] >= 4:
742
+ # ── Full-text indexes ──
743
+ for label, fields in [("Point", ["content"]),
744
+ # #244: AgentSession events populate name
745
+ # (not subject) — index both so session name
746
+ # matches surface through FTS.
747
+ ("Event", ["subject", "name"]),
748
+ ("Subject", ["name"]),
749
+ ("Document", ["_searchText"])]: # #125 Document FTS
750
+ try:
751
+ fields_sql = ", ".join(f"'{f}'" for f in fields)
752
+ self.g.query(f"CALL db.idx.fulltext.createNodeIndex('{label}', {fields_sql})")
753
+ except Exception as e:
754
+ msg = str(e).lower()
755
+ if "already" in msg:
756
+ if label == "Event":
757
+ # #244: legacy subject-only Event FTS index —
758
+ # migrate to include name ONCE (persisted DB
759
+ # marker, not a per-process flag: a process-local
760
+ # bool re-drops+recreates the index on every
761
+ # restart/worker, causing churn + a drop→recreate
762
+ # crash window where Event FTS degrades).
763
+ # FalkorDBLite embedded lacks dropIndex — leave
764
+ # subject-only there (name search still covered by
765
+ # the keyword fallback + vector strategies).
766
+ try:
767
+ done = self.g.query(
768
+ "MATCH (m:Meta {key:'event_fts_v2'}) RETURN 1"
769
+ ).result_set
770
+ if not done:
771
+ self.g.query("CALL db.idx.fulltext.dropIndex('Event')")
772
+ self.g.query("CALL db.idx.fulltext.createNodeIndex('Event', 'subject', 'name')")
773
+ self.g.query(
774
+ "MERGE (m:Meta {key:'event_fts_v2'}) SET m.v = true"
775
+ )
776
+ except Exception:
777
+ pass
778
+ else:
779
+ import logging
780
+ logging.getLogger(__name__).warning(
781
+ "Failed to create fulltext index on %s.%s: %s", label, fields, e)
782
+
783
+ # ── Vector index (HNSW) — Docker/server FalkorDB only (#7764) ──
784
+ # Embedded mode (redislite) uses brute-force vec.euclideanDistance instead.
785
+ # HNSW requires RediSearch module, not bundled with redislite.
786
+ if not getattr(self, '_is_embedded', False):
787
+ try:
788
+ self.g.query(
789
+ "CALL db.idx.vector.createNodeIndex('Point', 'embedding', 384, 'HNSW')"
790
+ )
791
+ except Exception as e:
792
+ msg = str(e).lower()
793
+ if "already" in msg:
794
+ pass
795
+ else:
796
+ import logging
797
+ logging.getLogger(__name__).warning(
798
+ "Failed to create vector index on Point.embedding: %s", e)
799
+ else:
800
+ import logging
801
+ logging.getLogger(__name__).info(
802
+ "Skipping FTS and vector indexes: FalkorDB %s < 4.x",
803
+ '.'.join(map(str, _ver)))
804
+
805
+ def backfill_document_search_text(self) -> int:
806
+ """#125: set _searchText=title on Documents missing it (idempotent).
807
+
808
+ Covers pre-existing Documents created before the capture-fields change.
809
+ Returns the number of Documents backfilled.
810
+ """
811
+ rows = self.g.query(
812
+ "MATCH (d:Document) WHERE d._searchText IS NULL "
813
+ "SET d._searchText = coalesce(d.title, '') "
814
+ "RETURN count(d)"
815
+ ).result_set
816
+ return rows[0][0] if rows else 0
817
+
818
+ def close(self) -> None:
819
+ """Close the underlying DB connection idempotently.
820
+
821
+ Lifecycle hardening (plan Task 4): idempotent (2nd call no-op),
822
+ registered via weakref.finalize so GC cleans up without explicit
823
+ close, and atexit-registered so normal process exit never orphans.
824
+ """
825
+ if getattr(self, "_closed", False):
826
+ return
827
+ self._closed = True
828
+ try:
829
+ self.db.close()
830
+ except Exception:
831
+ pass
832
+
833
+ def __enter__(self) -> "FalkorProjection":
834
+ return self
835
+
836
+ def __exit__(self, exc_type, exc, tb) -> None:
837
+ self.close()
838
+
839
+ def _revise_point(self, ev: dict, set_updated_at: bool = False) -> None:
840
+ """Apply PointRevised event — update content, context, and re-compute embedding."""
841
+ new_content = ev.get("new_content")
842
+ new_context = ev.get("new_context")
843
+ pid = ev.get("id") or ev["event_id"]
844
+ params: dict = {"id": pid, "c": new_content}
845
+
846
+ # Re-compute embedding when content changes (even to empty — wipe stale).
847
+ # Always set params["embedding"] so SET overwrites any stale value;
848
+ # on compute failure, set to None rather than preserving old embedding (#19).
849
+ if new_content is not None:
850
+ try:
851
+ from tortoise.embeddings import compute_embedding
852
+ emb = compute_embedding(new_content) if new_content else None
853
+ params["embedding"] = emb # None = wipe stale embedding for empty content
854
+ except Exception:
855
+ params["embedding"] = None # wipe stale embedding on failure (#19)
856
+
857
+ set_clauses = ["n.content = coalesce($c, n.content)"]
858
+ # Phase 2 #49: context removed — new_context no longer written
859
+ if "embedding" in params:
860
+ set_clauses.append("n.embedding = $embedding")
861
+ if set_updated_at:
862
+ set_clauses.append("n.updatedAt = $now")
863
+ params["now"] = _now_iso()
864
+
865
+ self.g.query(
866
+ f"MATCH (n:Point {{id:$id}}) SET {', '.join(set_clauses)}",
867
+ params=params,
868
+ )
869
+
870
+ def list_graphs(self) -> list[str]:
871
+ """List all graph names in the database."""
872
+ return self.db.list_graphs()
873
+
874
+ # ── SVBP integration (Gate 4) ─────────────────────────────────
875
+
876
+ def extract_svbp_factors(self):
877
+ """Extract factor list for TortoiseSVBP from the graph.
878
+
879
+ Returns (factors, evidence) where:
880
+ factors = [(op_id, op_type, [input_ids], weight), ...]
881
+ evidence = {claim_id: (alpha, beta), ...}
882
+ """
883
+ rows = self.g.query(
884
+ "MATCH (o:Point) WHERE o.is_operator = true "
885
+ "RETURN o.id, o.op_type"
886
+ ).result_set
887
+
888
+ factors = []
889
+ for op_id, op_type in rows:
890
+ input_rows = self.g.query(
891
+ "MATCH (o:Point {id:$oid})-[r:IMPL|NAND]->(c:Point) "
892
+ "RETURN c.id ORDER BY c.id",
893
+ params={"oid": op_id},
894
+ ).result_set
895
+ input_ids = [r[0] for r in input_rows]
896
+ if len(input_ids) >= 2:
897
+ weight = 3.0 if op_type == "NAND" else 1.0
898
+ factors.append((op_id, op_type, input_ids, weight))
899
+
900
+ return factors, {}
901
+
902
+ def get_svbp(self, **svbp_kwargs):
903
+ """Create and run TortoiseSVBP on the current graph.
904
+
905
+ Returns a TortoiseSVBP instance with converged beliefs.
906
+ """
907
+ from tortoise.svbp import TortoiseSVBP
908
+ factors, evidence = self.extract_svbp_factors()
909
+ if not factors:
910
+ return None
911
+ svbp = TortoiseSVBP(**svbp_kwargs)
912
+ svbp.run(factors, evidence=evidence)
913
+ return svbp