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,311 @@
1
+ """Edge creation and linking methods for FalkorProjection."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import datetime, timezone
5
+
6
+
7
+ def _now_iso() -> str:
8
+ return datetime.now(timezone.utc).isoformat()
9
+
10
+
11
+ class _EdgeHandlers:
12
+ """Mixin: edge creation, about edges, source linking, edge stats."""
13
+
14
+ def _create_edges(self, p: dict) -> None:
15
+ """Create typed edges for an operator Point. Auto-creates stub nodes
16
+ for missing source Points referenced by short IDs (#6713)."""
17
+ op = p["operator"]
18
+ rel_type = {"NAND": "NAND", "IMPL": "IMPL",
19
+ "composedOf": "hasPart", "decomposesInto": "hasPart",
20
+ "contains": "hasPart", "wraps": "hasPart"}.get(op["op_type"])
21
+ import logging as _logging
22
+ _log = _logging.getLogger(__name__)
23
+ for idx, src in enumerate(op["inputs"]):
24
+ # ponytail: auto-create stub if source Point doesn't exist.
25
+ # Short numeric IDs are orphan refs from cross-file wiring scripts.
26
+ if len(src) < 20: # short IDs (non-ULID) are suspect
27
+ exists = self.g.query(
28
+ "MATCH (s:Point {id:$sid}) RETURN count(s) > 0",
29
+ params={"sid": src}
30
+ ).result_set[0][0]
31
+ if not exists:
32
+ # #329: bounded stub auto-creation — at the per-instance cap
33
+ # we STOP creating stubs and SKIP the edge to the missing
34
+ # node (fail-safe: no partial edge, no crash, warning logged).
35
+ if getattr(self, "_autocreated_stubs", 0) >= getattr(
36
+ self, "_max_autocreated_stubs", 500):
37
+ _log.warning(
38
+ "stub auto-creation cap reached (%d) — skipping "
39
+ "missing source %r (edge not created)",
40
+ getattr(self, "_max_autocreated_stubs", 500), src,
41
+ )
42
+ continue
43
+ self.g.query(
44
+ "CREATE (s:Point {id:$sid}) "
45
+ "SET s.content='[missing]', "
46
+ " s.is_operator=false",
47
+ params={"sid": src}
48
+ )
49
+ self._autocreated_stubs = getattr(self, "_autocreated_stubs", 0) + 1
50
+ if rel_type is not None:
51
+ # Known op_type → typed edge + reverse INPUT
52
+ self.g.query(
53
+ f"MATCH (o:Point {{id:$oid}}) "
54
+ f"MATCH (s:Point {{id:$sid}}) "
55
+ f"MERGE (o)-[:{rel_type} {{idx:$idx}}]->(s) "
56
+ f"MERGE (s)-[:INPUT {{idx:$idx}}]->(o)",
57
+ params={"oid": p["id"], "sid": src, "idx": idx},
58
+ )
59
+ else:
60
+ # Unknown op_type → INPUT edge only
61
+ self.g.query(
62
+ "MATCH (o:Point {id:$oid}) "
63
+ "MATCH (s:Point {id:$sid}) "
64
+ "MERGE (o)-[:INPUT {idx:$idx}]->(s) "
65
+ "MERGE (s)-[:INPUT {idx:$idx}]->(o)",
66
+ params={"oid": p["id"], "sid": src, "idx": idx},
67
+ )
68
+
69
+ def _create_about_edges(self, source_id: str, entity_name: str) -> None:
70
+ """Link entity (Point, Document, Event, or Object) to a named entity.
71
+
72
+ Auto-detects entity type from the legacy flat aboutEntities list.
73
+ Tries Subject → Object → Action → Event → Document, creates stub if none found.
74
+ ONTOLOGY v2.5 §2.2: Point/Doc/Event → Subject/Object/Action; Point/Doc → Event; Event → Point/Document.
75
+ #125: source MATCH is label-agnostic so Document/Event sources work too.
76
+ """
77
+ # Try Subject
78
+ if self._try_about_edge(source_id, entity_name, 'Subject', 'aboutSubject', 'subjectKind', 'other'):
79
+ return
80
+ # Try Object
81
+ if self._try_about_edge(source_id, entity_name, 'Object', 'aboutObject', 'objectKind', 'other'):
82
+ return
83
+ # Try Event
84
+ if self._try_about_edge(source_id, entity_name, 'Event', 'aboutEvent', 'eventKind', 'other'):
85
+ return
86
+ # Try Document
87
+ if self._try_about_edge(source_id, entity_name, 'Document', 'aboutDocument', 'documentKind', 'other'):
88
+ return
89
+ # Try Point (for Event→Point reverse direction)
90
+ if self._try_about_edge(source_id, entity_name, 'Point', 'aboutPoint', 'pointKind', 'statement'):
91
+ return
92
+ # Neither exists — default to Subject stub (label-agnostic source)
93
+ self.g.query(
94
+ "MERGE (s:Subject {name:$name}) "
95
+ "ON CREATE SET s.id=$name, s.subjectKind='other'",
96
+ params={"name": entity_name},
97
+ )
98
+ srcs = self._resolve_entity(source_id, by_id=True)
99
+ for n in srcs:
100
+ self.g.query(
101
+ f"MATCH (n:{n['label']} {{{n['key']}:$pid}}), (s:Subject {{name:$name}}) "
102
+ f"MERGE (n)-[:aboutSubject]->(s)",
103
+ params={"pid": n["value"], "name": entity_name},
104
+ )
105
+
106
+ def _try_about_edge(self, source_id: str, target_name: str,
107
+ label: str, edge_type: str, kind_field: str, kind_default: str) -> bool:
108
+ """Try to create an about* edge to a named entity. Returns True if found.
109
+
110
+ For Document nodes, matches against both ``name`` and ``title`` properties
111
+ (Documents store their display name in ``title`` per _upsert_document).
112
+ """
113
+ # Documents use 'title' as their display name (#211)
114
+ if label == 'Document':
115
+ r = self.g.query(
116
+ f"MATCH (e:{label}) WHERE e.name = $name OR e.title = $name "
117
+ "RETURN coalesce(e.title, e.name, $name) LIMIT 1",
118
+ params={"name": target_name},
119
+ ).result_set
120
+ else:
121
+ r = self.g.query(
122
+ f"MATCH (e:{label} {{name:$name}}) RETURN e.name LIMIT 1",
123
+ params={"name": target_name},
124
+ ).result_set
125
+ if r:
126
+ for n in self._resolve_entity(source_id, by_id=True):
127
+ if label == 'Document':
128
+ self.g.query(
129
+ f"MATCH (n:{n['label']} {{{n['key']}:$sid}}), (e:{label}) "
130
+ f"WHERE e.name = $name OR e.title = $name "
131
+ f"MERGE (n)-[:{edge_type}]->(e)",
132
+ params={"sid": n["value"], "name": target_name},
133
+ )
134
+ else:
135
+ self.g.query(
136
+ f"MATCH (n:{n['label']} {{{n['key']}:$sid}}), (e:{label} {{name:$name}}) "
137
+ f"MERGE (n)-[:{edge_type}]->(e)",
138
+ params={"sid": n["value"], "name": target_name},
139
+ )
140
+ return True
141
+ return False
142
+
143
+ def create_about_edge(self, source_id: str, target_id: str, edge_type: str) -> bool:
144
+ """Create a specific about* edge by source/target IDs. Validates edge type.
145
+
146
+ Args:
147
+ source_id: ID of source node (Point, Document, or Event)
148
+ target_id: ID of target node
149
+ edge_type: one of aboutSubject, aboutObject, aboutEvent, aboutPoint, aboutDocument
150
+
151
+ Returns True if edge was created.
152
+ """
153
+ valid = {'aboutSubject', 'aboutObject', 'aboutEvent', 'aboutPoint', 'aboutDocument'}
154
+ if edge_type not in valid:
155
+ raise ValueError(f"Invalid about edge type: {edge_type}. Must be one of {valid}")
156
+
157
+ # Resolve endpoints via index-backed labeled lookups (issue #327).
158
+ # Source predicate is id-only; target is id OR eventId (legacy OR-set).
159
+ sources = self._resolve_entity(source_id, by_id=True)
160
+ targets = self._resolve_entity(target_id, by_id=True, by_eventId=True)
161
+ if not sources or not targets:
162
+ return False
163
+ created = False
164
+ for s in sources:
165
+ for t in targets:
166
+ r = self.g.query(
167
+ f"MATCH (s:{s['label']} {{{s['key']}:$sv}}) "
168
+ f"MATCH (t:{t['label']} {{{t['key']}:$tv}}) "
169
+ f"MERGE (s)-[:{edge_type}]->(t) "
170
+ f"RETURN count(*) > 0",
171
+ params={"sv": s["value"], "tv": t["value"]},
172
+ )
173
+ if r.result_set and r.result_set[0][0]:
174
+ created = True
175
+ return created
176
+
177
+ def _link_source(self, point_id: str, source_ref: str, source_kind: str = "document") -> None:
178
+ """Link Point → Source via extractedFrom edge (Ontology v2.5).
179
+
180
+ Creates stub Source if missing, keyed on url. sourceKind defaults to 'document'
181
+ but connectors pass specific values (github_issue, slack_message, linear_card, etc.).
182
+ """
183
+ self.g.query(
184
+ "MERGE (s:Source {url:$url}) "
185
+ "ON CREATE SET s.sourceKind=$sk, s.title=$url, "
186
+ " s.contentHash='', s.ingestedAt=$now",
187
+ params={"url": source_ref, "sk": source_kind, "now": _now_iso()},
188
+ )
189
+ self.g.query(
190
+ "MATCH (n:Point {id:$pid}), (s:Source {url:$url}) "
191
+ "MERGE (n)-[:extractedFrom]->(s)",
192
+ params={"pid": point_id, "url": source_ref},
193
+ )
194
+
195
+ def link_source_to_entity(self, source_url: str, entity_id: str, entity_label: str, source_kind: str = "document") -> None:
196
+ """Create Source → Entity references edge (Ontology v3.1 §3.4).
197
+
198
+ Auto-creates the Source node if it doesn't exist (MERGE + ON CREATE SET)
199
+ so the edge works even when no Point extracted the source yet (#205).
200
+
201
+ Args:
202
+ source_url: the Source node's url (auto-created if missing)
203
+ entity_id: the Document/Event/Object node id the source references
204
+ entity_label: the entity label (Document|Event|Object) for the MATCH
205
+ source_kind: sourceKind to set on auto-created Source (default: "document")
206
+
207
+ Raises:
208
+ ValueError: if entity_label is not one of Document, Event, Object
209
+ (Action was dissolved in Ontology v3.0).
210
+ """
211
+ valid = {"Document", "Event", "Object"}
212
+ if entity_label not in valid:
213
+ raise ValueError(
214
+ f"Invalid entity_label: {entity_label}. Must be one of {valid} "
215
+ f"(Action was dissolved in Ontology v3.0)."
216
+ )
217
+ # MERGE Source with auto-create (mirrors _link_source) — #205
218
+ self.g.query(
219
+ "MERGE (s:Source {url:$url}) "
220
+ "ON CREATE SET s.sourceKind=$sk, s.title=$url, "
221
+ " s.contentHash='', s.ingestedAt=$now",
222
+ params={"url": source_url, "sk": source_kind, "now": _now_iso()},
223
+ )
224
+ self.g.query(
225
+ f"MATCH (s:Source {{url:$url}}), (e:{entity_label} {{id:$eid}}) "
226
+ f"MERGE (s)-[:references]->(e)",
227
+ params={"url": source_url, "eid": entity_id},
228
+ )
229
+
230
+ # ponytail: SDK compat alias (Phase 1b will rename caller)
231
+ _link_extracted_from = _link_source
232
+
233
+ def edge_stats(self) -> dict:
234
+ """Return {operators, impl_edges, nand_edges, input_edges} for diagnostics."""
235
+ ops = self.g.query(
236
+ "MATCH (n:Point) WHERE n.is_operator = true RETURN count(n)"
237
+ ).result_set[0][0]
238
+ impl = self.g.query(
239
+ "MATCH ()-[r:IMPL]->() RETURN count(r)"
240
+ ).result_set[0][0]
241
+ nand = self.g.query(
242
+ "MATCH ()-[r:NAND]->() RETURN count(r)"
243
+ ).result_set[0][0]
244
+ inp = self.g.query(
245
+ "MATCH ()-[r:INPUT]->() RETURN count(r)"
246
+ ).result_set[0][0]
247
+ return {"operators": ops, "impl_edges": impl, "nand_edges": nand,
248
+ "input_edges": inp}
249
+
250
+ def create_edge(self, source_id: str, target_id: str, predicate: str) -> bool:
251
+ """Create a named edge between two entities by their IDs.
252
+ Matches target by id OR eventId (Event nodes use eventId as key)."""
253
+ valid_predicates = {
254
+ 'performs', 'produces', 'uses', 'authoredBy', 'ownedBy', 'managedBy',
255
+ 'hasMember', 'holdsRole', 'memberOf', 'reportsTo',
256
+ 'participatesIn', 'hasPart', 'related', 'dependsOn', 'references',
257
+ 'wasDerivedFrom'
258
+ }
259
+ if predicate not in valid_predicates:
260
+ raise ValueError(f"Unknown predicate: {predicate}")
261
+ # Resolve endpoints via index-backed labeled lookups (issue #327).
262
+ # Source OR-set: id | eventId | url ; target OR-set: id | eventId —
263
+ # matching the legacy predicates exactly (a url-only stub Source is
264
+ # therefore NOT a valid target, preserving prior behavior).
265
+ sources = self._resolve_entity(source_id, by_id=True, by_eventId=True, by_url=True)
266
+ targets = self._resolve_entity(target_id, by_id=True, by_eventId=True)
267
+ if not sources or not targets:
268
+ return False
269
+ created = False
270
+ for s in sources:
271
+ for t in targets:
272
+ r = self.g.query(
273
+ f"MATCH (s:{s['label']} {{{s['key']}:$sv}}) "
274
+ f"MATCH (t:{t['label']} {{{t['key']}:$tv}}) "
275
+ f"MERGE (s)-[:{predicate}]->(t) RETURN count(*) > 0",
276
+ params={"sv": s["value"], "tv": t["value"]},
277
+ )
278
+ if r.result_set and r.result_set[0][0]:
279
+ created = True
280
+ return created
281
+
282
+ def create_owned_by(self, entity_id: str, subject_id: str) -> bool:
283
+ """Create ownedBy edge with circular ownership DAG check."""
284
+ # Resolve endpoints by id (index-backed, issue #327); the varlen
285
+ # traversal itself has no index in FalkorDB and is accepted.
286
+ # All resolved (s, t) pairs are checked (original cartesian semantics).
287
+ sources = self._resolve_entity(subject_id, by_id=True)
288
+ targets = self._resolve_entity(entity_id, by_id=True)
289
+ found_cycle = False
290
+ for s in sources:
291
+ for t in targets:
292
+ cycle = self.g.query(
293
+ f"MATCH (s:{s['label']} {{{s['key']}:$sid}}) "
294
+ f"MATCH (t:{t['label']} {{{t['key']}:$tid}}) "
295
+ f"MATCH path = (s)-[:ownedBy*1..10]->(t) RETURN count(path) > 0",
296
+ params={"sid": s["value"], "tid": t["value"]},
297
+ )
298
+ if cycle.result_set and cycle.result_set[0][0]:
299
+ found_cycle = True
300
+ break
301
+ if found_cycle:
302
+ break
303
+ if found_cycle:
304
+ raise ValueError(f"Circular ownership: {subject_id} already owned by {entity_id}")
305
+ return self.create_edge(entity_id, subject_id, 'ownedBy')
306
+
307
+ def create_managed_by(self, entity_id: str, subject_id: str) -> bool:
308
+ return self.create_edge(entity_id, subject_id, 'managedBy')
309
+
310
+ def create_authored_by(self, entity_id: str, subject_id: str) -> bool:
311
+ return self.create_edge(entity_id, subject_id, 'authoredBy')