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
tortoise/navigation.py ADDED
@@ -0,0 +1,216 @@
1
+ """Navigation — entity-centric graph traversal and profiling.
2
+
3
+ entityProfile: BFS from entity, categorize connected nodes by type.
4
+ tortoise_traverse: multi-hop traversal following ALL relationship types.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import re
9
+ from typing import Any
10
+
11
+
12
+ #: Root-lookup branches for _resolve_root (issue #327). Every branch is a
13
+ #: labeled lookup so the planner uses Node By Index Scan instead of All Node
14
+ #: Scan. Mirrors the legacy `MATCH (n) WHERE n.id = $eid` semantics for the
15
+ #: canonical entity labels + Session: nodes are matched by their property id
16
+ #: (Event.id == eventId, so the eventId branch is equivalent; Source nodes
17
+ #: carry id except url-only ingestion stubs, which the legacy query also
18
+ #: never matched). Team/APIKey roots are intentionally out of scope (they
19
+ #: carry id but live in the registry graph / control plane).
20
+ _ROOT_BRANCHES = (
21
+ ("Point", "id"), ("Subject", "id"), ("Object", "id"),
22
+ ("Document", "id"), ("Source", "id"), ("Session", "id"),
23
+ ("Event", "eventId"),
24
+ )
25
+
26
+
27
+ def _resolve_root(g: Any, entity_id: str) -> tuple[str | None, dict]:
28
+ """Index-backed root lookup: returns (label, properties) or (None, {}).
29
+
30
+ One UNION query over labeled branches — each branch index-backed (#327).
31
+ """
32
+ union_q = " UNION ".join(
33
+ f"MATCH (n:{label}) WHERE n.{prop} = $eid "
34
+ f"RETURN '{label}' AS label, properties(n) AS props LIMIT 1"
35
+ for label, prop in _ROOT_BRANCHES
36
+ )
37
+ rows = g.query(union_q, params={"eid": entity_id}).result_set
38
+ if not rows:
39
+ return None, {}
40
+ label, props = rows[0][0], rows[0][1]
41
+ parsed = dict(props)
42
+ parsed["type"] = label
43
+ return label, parsed
44
+
45
+
46
+ #: Safe label-identifier pattern — fail-closed before interpolating a graph
47
+ #: label into Cypher (issue #327 security review). Node labels are created by
48
+ #: the app's own hardcoded MERGE statements today, but a future data-derived
49
+ #: label must never reach query text.
50
+ _SAFE_LABEL_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
51
+
52
+
53
+ #: Per-hop frontier-node match: label on the SOURCE side in BOTH directions.
54
+ #: (Verified: `MATCH (n:Point)<-[r]-(m)` -> Index Scan; the neighbor-labeled
55
+ #: form `MATCH (n)<-[r]-(m:Point)` degrades to All Node Scan — the trap.)
56
+ def _hop_query(label: str) -> str | None:
57
+ if not _SAFE_LABEL_RE.match(label or ""):
58
+ # Unknown label -> no nodes match (legacy behavior: the property-id
59
+ # lookup matched nothing for labels without an id property).
60
+ return None
61
+ return (
62
+ f"MATCH (n:{label} {{id:$eid}})-[r]->(m) "
63
+ f"WHERE NOT m.id IN $visited RETURN m, type(r) UNION "
64
+ f"MATCH (n:{label} {{id:$eid}})<-[r]-(m) "
65
+ f"WHERE NOT m.id IN $visited RETURN m, type(r)"
66
+ )
67
+
68
+
69
+ def entityProfile(
70
+ db: Any, # FalkorDB client (duck-typed: needs .select_graph())
71
+ graph_name: str, # e.g. "tortoise", "episodic"
72
+ entity_id: str,
73
+ hops: int = 2,
74
+ pointKind: str | None = None,
75
+ confidenceMin: float | None = None,
76
+ ) -> dict:
77
+ """BFS from an entity node, following all edge types up to `hops` depth.
78
+
79
+ Returns {entity: {...}, connected: {points, documents, events, subjects, objects}}.
80
+ Categorizes connected nodes by label, optionally filtering by pointKind and confidenceMin.
81
+ """
82
+ g = db.select_graph(graph_name)
83
+
84
+ # 1. Fetch the root entity (index-backed labeled union, #327)
85
+ root_label, root = _resolve_root(g, entity_id)
86
+ if root_label is None:
87
+ return {"entity": {}, "connected": {"points": [], "documents": [],
88
+ "events": [], "subjects": [], "objects": []}}
89
+
90
+ # 2. BFS — follow all edges for `hops` levels. Frontier tracks (id, label);
91
+ # the per-hop query binds the frontier node's label on the SOURCE side
92
+ # so every hop uses the id range index (issue #327).
93
+ visited: set[str] = {entity_id}
94
+ frontier: list[tuple[str, str]] = [(entity_id, root_label)]
95
+ connected: list[dict] = []
96
+
97
+ for _ in range(hops):
98
+ next_frontier: list[tuple[str, str]] = []
99
+ for fid, flabel in frontier:
100
+ hq = _hop_query(flabel)
101
+ rows = (g.query(hq, params={"eid": fid, "visited": list(visited)})
102
+ .result_set if hq else [])
103
+ for row in rows:
104
+ node = _parse_node(row[0])
105
+ rel_type = row[1] if len(row) > 1 else None
106
+ nid = node.get("id")
107
+ nlabel = node.get("type")
108
+ if nid and nid not in visited:
109
+ node["_relationship"] = rel_type
110
+ connected.append(node)
111
+ visited.add(nid)
112
+ next_frontier.append((nid, nlabel))
113
+ frontier = next_frontier
114
+
115
+ # 3. Categorize by label, apply filters
116
+ result: dict[str, list] = {
117
+ "points": [], "documents": [], "events": [], "subjects": [], "objects": [],
118
+ }
119
+ for node in connected:
120
+ label = node.get("type", "").lower()
121
+ # Apply filters
122
+ if pointKind and node.get("pointKind") != pointKind:
123
+ continue
124
+ if confidenceMin is not None:
125
+ conf = node.get("confidence", 0.5)
126
+ if conf < confidenceMin:
127
+ continue
128
+ # Categorize
129
+ if label == "point":
130
+ result["points"].append(node)
131
+ elif label == "document":
132
+ result["documents"].append(node)
133
+ elif label == "event":
134
+ result["events"].append(node)
135
+ elif label == "subject":
136
+ result["subjects"].append(node)
137
+ elif label == "object":
138
+ result["objects"].append(node)
139
+ else:
140
+ # Unknown type → stash under points as fallback
141
+ result["points"].append(node)
142
+
143
+ return {"entity": root, "connected": result}
144
+
145
+
146
+ def tortoise_traverse(
147
+ db: Any, # FalkorDB client
148
+ graph_name: str, # e.g. "tortoise"
149
+ entity_id: str,
150
+ max_hops: int = 2,
151
+ ) -> dict:
152
+ """Multi-hop graph traversal from an entity following ALL relationship types.
153
+
154
+ Returns {entity: {...}, nodes: [{"node": {...}, "relationship": "...", "depth": N}, ...]}.
155
+ Each connected node includes the relationship type and BFS depth.
156
+ """
157
+ g = db.select_graph(graph_name)
158
+
159
+ # Fetch root (index-backed labeled union, #327)
160
+ root_label, root = _resolve_root(g, entity_id)
161
+
162
+ # BFS with depth tracking; frontier carries (id, label, depth) so each
163
+ # per-hop query can bind the source label for index-backed lookups.
164
+ visited: set[str] = {entity_id}
165
+ frontier: list[tuple[str, str, int]] = (
166
+ [(entity_id, root_label, 0)] if root_label else [])
167
+ nodes: list[dict] = []
168
+
169
+ for _ in range(max_hops):
170
+ next_frontier: list[tuple[str, str, int]] = []
171
+ for fid, flabel, depth in frontier:
172
+ hq = _hop_query(flabel)
173
+ rows = (g.query(hq, params={"eid": fid, "visited": list(visited)})
174
+ .result_set if hq else [])
175
+ for row in rows:
176
+ node = _parse_node(row[0])
177
+ rel_type = row[1] if len(row) > 1 else None
178
+ nid = node.get("id")
179
+ nlabel = node.get("type")
180
+ if nid and nid not in visited:
181
+ nodes.append({
182
+ "node": node,
183
+ "relationship": rel_type,
184
+ "depth": depth + 1,
185
+ })
186
+ visited.add(nid)
187
+ next_frontier.append((nid, nlabel, depth + 1))
188
+ frontier = next_frontier
189
+
190
+ return {"entity": root, "nodes": nodes}
191
+
192
+
193
+ # ── Shared helper ──────────────────────────────────────
194
+
195
+ def _parse_node(node: Any) -> dict:
196
+ """Parse FalkorDB Node → flat dict {id, type, ...properties}.
197
+
198
+ Handles FalkorDB Node objects (1.6+) and raw list form for testing.
199
+
200
+ Prefers the public ``id`` property (ULID) from node properties over the
201
+ internal FalkorDB numeric node ID. Falls back to the internal ID only
202
+ when nodes lack an ``id`` property (edge case, typically test mocks).
203
+ See #44: traverse was leaking internal IDs downstream.
204
+ """
205
+ if hasattr(node, 'properties'):
206
+ props = dict(node.properties)
207
+ if "id" not in props:
208
+ props["id"] = str(node.id)
209
+ props["type"] = node.labels[0] if node.labels else "unknown"
210
+ return props
211
+ # Raw list form: [id, [labels], [[k, v], ...]]
212
+ props = {k: v for k, v in node[2]}
213
+ if "id" not in props:
214
+ props["id"] = str(node[0])
215
+ props["type"] = node[1][0] if node[1] else "unknown"
216
+ return props