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.
- tortoise/__init__.py +45 -0
- tortoise/__main__.py +1865 -0
- tortoise/analyze.py +473 -0
- tortoise/api.py +303 -0
- tortoise/archived/search_legacy.py +31 -0
- tortoise/audit.py +236 -0
- tortoise/audit_events.py +284 -0
- tortoise/auth.py +107 -0
- tortoise/backup.py +155 -0
- tortoise/config.py +99 -0
- tortoise/connector_loader.py +74 -0
- tortoise/connectors/__init__.py +5 -0
- tortoise/connectors/github.py +432 -0
- tortoise/connectors/github_docs.py +146 -0
- tortoise/connectors/linear.py +199 -0
- tortoise/connectors/slack.py +222 -0
- tortoise/consistency.py +132 -0
- tortoise/crypto.py +52 -0
- tortoise/deployment.py +62 -0
- tortoise/domain_loader.py +142 -0
- tortoise/dream.py +153 -0
- tortoise/embedded_reaper.py +744 -0
- tortoise/embeddings.py +227 -0
- tortoise/ep.py +534 -0
- tortoise/exceptions.py +16 -0
- tortoise/extractor.py +945 -0
- tortoise/hosted_api.py +1982 -0
- tortoise/hosted_middleware.py +22 -0
- tortoise/idempotency.py +39 -0
- tortoise/ids.py +23 -0
- tortoise/indexer/github_indexer.py +129 -0
- tortoise/ingest.py +614 -0
- tortoise/log.py +29 -0
- tortoise/m0.py +50 -0
- tortoise/mcp_auth.py +337 -0
- tortoise/mcp_client.py +108 -0
- tortoise/mcp_server.py +1356 -0
- tortoise/memory_orchestrator.py +492 -0
- tortoise/memory_scope.py +15 -0
- tortoise/migrate_db.py +244 -0
- tortoise/migrate_kinds.py +141 -0
- tortoise/mining.py +338 -0
- tortoise/models.py +109 -0
- tortoise/monitoring.py +133 -0
- tortoise/navigation.py +216 -0
- tortoise/pack_registry.py +767 -0
- tortoise/pipeline_cli.py +197 -0
- tortoise/projection/__init__.py +913 -0
- tortoise/projection/edges.py +311 -0
- tortoise/projection/entities.py +521 -0
- tortoise/projection/grounding.py +95 -0
- tortoise/projection/propagation.py +114 -0
- tortoise/projection.py +37 -0
- tortoise/quadrature.py +90 -0
- tortoise/query_suggestions.py +194 -0
- tortoise/quota.py +163 -0
- tortoise/ranking.py +280 -0
- tortoise/render.py +108 -0
- tortoise/scripts/manifest.py +67 -0
- tortoise/sdk.py +4713 -0
- tortoise/search_engine.py +887 -0
- tortoise/security.py +268 -0
- tortoise/selfhost.py +157 -0
- tortoise/selfhost_api.py +201 -0
- tortoise/session_continuity.py +82 -0
- tortoise/session_indexer.py +569 -0
- tortoise/shared_state/__init__.py +20 -0
- tortoise/shared_state/concurrency.py +113 -0
- tortoise/shared_state/event_log.py +192 -0
- tortoise/shared_state/events.py +150 -0
- tortoise/shared_state/monitoring.py +87 -0
- tortoise/shared_state/recovery.py +126 -0
- tortoise/shared_state/tests/__init__.py +15 -0
- tortoise/shared_state/tests/test_concurrency.py +123 -0
- tortoise/shared_state/tests/test_events.py +145 -0
- tortoise/shared_state/tests/test_monitoring.py +54 -0
- tortoise/shared_state/tests/test_recovery.py +181 -0
- tortoise/source_credibility.py +306 -0
- tortoise/svbp.py +446 -0
- tortoise/taxonomy.py +71 -0
- tortoise/test_cross_ontology.py +180 -0
- tortoise/test_tortoise_client.py +206 -0
- tortoise/tool_registry.py +805 -0
- tortoise/tortoise_client.py +262 -0
- tortoise/verify_ontology.py +154 -0
- tortoise/version_vector.py +97 -0
- tortoise/weights.py +61 -0
- tortoise_graph-0.2.0.dist-info/METADATA +152 -0
- tortoise_graph-0.2.0.dist-info/RECORD +93 -0
- tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
- tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
- tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
- tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
"""Memory Orchestrator — cross-ontology query routing and merge.
|
|
2
|
+
|
|
3
|
+
Phase A: episodic + epistemic. Phase B: add semantic + docIndex (add 2 entries to dicts).
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from concurrent.futures import Future, ThreadPoolExecutor, TimeoutError
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
# ── Data ──────────────────────────────────────────────
|
|
12
|
+
|
|
13
|
+
ROUTING_TABLE_WRITE: dict[str, list[str]] = {
|
|
14
|
+
"episodic": ["EventRecorded", "SubjectAdded", "ActionPerformed"],
|
|
15
|
+
"epistemic": ["PointAdded", "OperatorAdded", "PointRevised"],
|
|
16
|
+
"semantic": ["DocumentCreated", "SubjectAdded", "ObjectRegistered"],
|
|
17
|
+
"docIndex": ["DocumentCreated", "DocumentUpdated"],
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
ROUTING_TABLE_READ: dict[str, list[str]] = {
|
|
21
|
+
"whatHappened": ["episodic"],
|
|
22
|
+
"timeline": ["episodic"],
|
|
23
|
+
"beliefs": ["epistemic"],
|
|
24
|
+
"claimsAbout": ["epistemic"],
|
|
25
|
+
"entityLookup": ["semantic"],
|
|
26
|
+
"findDocs": ["docIndex"],
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
# ponytail: one Cypher template per ontology. Extend here for Phase B.
|
|
30
|
+
ONTOLOGY_CYPHER: dict[str, str] = {
|
|
31
|
+
"episodic": "MATCH (e:Event) RETURN e ORDER BY e.startedAt DESC LIMIT 50",
|
|
32
|
+
"epistemic": "MATCH (p:Point) RETURN p ORDER BY p.createdAt DESC LIMIT 50",
|
|
33
|
+
"semantic": "MATCH (n) WHERE n:Subject OR n:Object RETURN n LIMIT 50",
|
|
34
|
+
"docIndex": "MATCH (d:Document) RETURN d ORDER BY d.createdAt DESC LIMIT 50",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class MergeResult:
|
|
40
|
+
results: list[dict] = field(default_factory=list)
|
|
41
|
+
byOntology: dict[str, list[dict]] = field(default_factory=dict)
|
|
42
|
+
conflicts: list[dict] = field(default_factory=list)
|
|
43
|
+
failedOntologies: list[str] = field(default_factory=list)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def totalByOntology(self) -> dict[str, int]:
|
|
47
|
+
return {ont: len(rows) for ont, rows in self.byOntology.items()}
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def mergedCount(self) -> int:
|
|
51
|
+
return len(self.results)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class OrchestratorError(Exception):
|
|
55
|
+
"""All ontologies failed. Caller can catch specifically vs RuntimeError."""
|
|
56
|
+
def __init__(self, failures: dict[str, str]):
|
|
57
|
+
self.failures = failures
|
|
58
|
+
super().__init__(f"All ontologies failed: {failures}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# ── Routing ───────────────────────────────────────────
|
|
62
|
+
|
|
63
|
+
def routeWrite(eventType: str) -> list[str]:
|
|
64
|
+
"""Return ontologies that handle this event type."""
|
|
65
|
+
return [ont for ont, types in ROUTING_TABLE_WRITE.items() if eventType in types]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def routeRead(patterns: list[str]) -> list[str]:
|
|
69
|
+
"""Return deduplicated union of ontologies for multiple patterns."""
|
|
70
|
+
ontologies: set[str] = set()
|
|
71
|
+
for p in patterns:
|
|
72
|
+
ontologies.update(ROUTING_TABLE_READ.get(p, []))
|
|
73
|
+
return list(ontologies)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ── NL Translation ─────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
# ponytail: keyword classifier. Replace with LLM dispatch when accuracy < 80%.
|
|
79
|
+
PATTERN_KEYWORDS: dict[str, list[str]] = {
|
|
80
|
+
"whatHappened": ["what happened", "what did", "show events", "recent"],
|
|
81
|
+
"timeline": ["timeline", "chronology", "sequence", "history of"],
|
|
82
|
+
"beliefs": ["what do we believe", "what is our position", "current thinking"],
|
|
83
|
+
"claimsAbout": ["claims about", "what about", "tell me about", "decisions about"],
|
|
84
|
+
"entityLookup": ["who is", "what is", "entity", "lookup"],
|
|
85
|
+
"findDocs": ["find docs", "documents about", "where is document", "show me docs"],
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def translateNL(query: str) -> tuple[list[str], dict[str, str]]:
|
|
90
|
+
"""NL query → (patterns, filters). Keyword-based classifier.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
patterns: matched pattern names (empty if no keywords match)
|
|
94
|
+
filters: always empty dict in Phase A (filter extraction deferred to Phase B)
|
|
95
|
+
"""
|
|
96
|
+
q = query.lower()
|
|
97
|
+
patterns: list[str] = []
|
|
98
|
+
for pattern, keywords in PATTERN_KEYWORDS.items():
|
|
99
|
+
if any(kw in q for kw in keywords):
|
|
100
|
+
patterns.append(pattern)
|
|
101
|
+
return patterns, {} # ponytail: filter extraction deferred to Phase B
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# ── Dispatch ──────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
def dispatch(
|
|
107
|
+
ontologies: list[str],
|
|
108
|
+
db: Any,
|
|
109
|
+
timeout: float = 5.0,
|
|
110
|
+
cypherOverrides: dict[str, str] | None = None,
|
|
111
|
+
cypherParams: dict | None = None,
|
|
112
|
+
) -> tuple[dict[str, list[dict]], dict[str, str]]:
|
|
113
|
+
"""Parallel dispatch to ontologies.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
(results, errors) — successful results keyed by ontology,
|
|
117
|
+
errors keyed by ontology with error string.
|
|
118
|
+
"""
|
|
119
|
+
cypherMap = {**ONTOLOGY_CYPHER, **(cypherOverrides or {})}
|
|
120
|
+
results: dict[str, list[dict]] = {}
|
|
121
|
+
errors: dict[str, str] = {}
|
|
122
|
+
|
|
123
|
+
if not ontologies:
|
|
124
|
+
return results, errors
|
|
125
|
+
|
|
126
|
+
import time
|
|
127
|
+
deadline = time.monotonic() + timeout
|
|
128
|
+
|
|
129
|
+
with ThreadPoolExecutor(max_workers=len(ontologies)) as ex:
|
|
130
|
+
# Submit all futures in parallel, then wait per-future with timeout
|
|
131
|
+
pending: dict[str, Future] = {}
|
|
132
|
+
for ont in ontologies:
|
|
133
|
+
if ont not in cypherMap:
|
|
134
|
+
errors[ont] = "no Cypher template"
|
|
135
|
+
continue
|
|
136
|
+
pending[ont] = ex.submit(_queryOntology, db, ont, cypherMap[ont], cypherParams)
|
|
137
|
+
|
|
138
|
+
for ont, f in pending.items():
|
|
139
|
+
remaining = deadline - time.monotonic()
|
|
140
|
+
if remaining <= 0:
|
|
141
|
+
errors[ont] = "timeout"
|
|
142
|
+
continue
|
|
143
|
+
try:
|
|
144
|
+
results[ont] = f.result(timeout=remaining)
|
|
145
|
+
except TimeoutError:
|
|
146
|
+
errors[ont] = "timeout"
|
|
147
|
+
except Exception as e:
|
|
148
|
+
errors[ont] = str(e)
|
|
149
|
+
|
|
150
|
+
if not results and errors:
|
|
151
|
+
raise OrchestratorError(errors)
|
|
152
|
+
return results, errors
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _queryOntology(db: Any, ontology: str, cypher: str, params: dict | None = None) -> list[dict]:
|
|
156
|
+
"""Execute Cypher against ontology graph.
|
|
157
|
+
|
|
158
|
+
Returns list of flat entity dicts with 'id', 'type', and properties.
|
|
159
|
+
Connection/auth errors propagate to dispatch error handling.
|
|
160
|
+
"""
|
|
161
|
+
g = db.select_graph(ontology)
|
|
162
|
+
if params:
|
|
163
|
+
rows = g.query(cypher, params=params).result_set
|
|
164
|
+
else:
|
|
165
|
+
rows = g.query(cypher).result_set
|
|
166
|
+
if not rows:
|
|
167
|
+
return []
|
|
168
|
+
return [_parseNode(row[0]) for row in rows]
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _parseNode(node: Any) -> dict:
|
|
172
|
+
"""Parse FalkorDB Node → flat dict {id, type, ...properties}.
|
|
173
|
+
|
|
174
|
+
FalkorDB 1.6+ returns Node objects with .id, .labels, .properties.
|
|
175
|
+
Also handles raw list form [id, [labels], [[k,v],...]] for testing.
|
|
176
|
+
"""
|
|
177
|
+
if hasattr(node, 'properties'):
|
|
178
|
+
# FalkorDB Node object
|
|
179
|
+
props = dict(node.properties)
|
|
180
|
+
props["id"] = str(node.id)
|
|
181
|
+
props["type"] = node.labels[0] if node.labels else "unknown"
|
|
182
|
+
return props
|
|
183
|
+
# Raw list form: [id, [labels], [[k, v], ...]]
|
|
184
|
+
props = {k: v for k, v in node[2]}
|
|
185
|
+
props["id"] = str(node[0])
|
|
186
|
+
props["type"] = node[1][0] if node[1] else "unknown"
|
|
187
|
+
return props
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
# ── Merge ─────────────────────────────────────────────
|
|
191
|
+
|
|
192
|
+
def merge(
|
|
193
|
+
results: dict[str, list[dict]],
|
|
194
|
+
errors: dict[str, str],
|
|
195
|
+
) -> MergeResult:
|
|
196
|
+
"""Union results with provenance tagging, entity dedup, conflict detection.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
results: {ontology: [entity dicts]} from dispatch
|
|
200
|
+
errors: {ontology: error string} from dispatch
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
MergeResult with provenance-tagged, deduplicated results and failed ontologies
|
|
204
|
+
"""
|
|
205
|
+
seen: dict[str, dict] = {} # entity ID → merged result
|
|
206
|
+
|
|
207
|
+
for ont, rows in results.items():
|
|
208
|
+
for row in rows:
|
|
209
|
+
eid = row.get("id")
|
|
210
|
+
if not eid:
|
|
211
|
+
continue
|
|
212
|
+
if eid in seen:
|
|
213
|
+
existing = seen[eid]
|
|
214
|
+
existing["sourceOntologies"].append(ont)
|
|
215
|
+
for key, val in row.items():
|
|
216
|
+
if key in ("id", "type"):
|
|
217
|
+
continue
|
|
218
|
+
if key in existing["properties"] and existing["properties"][key] != val:
|
|
219
|
+
existing["conflict"] = True
|
|
220
|
+
if existing["conflictDetail"] is None:
|
|
221
|
+
existing["conflictDetail"] = {}
|
|
222
|
+
if key not in existing["conflictDetail"]:
|
|
223
|
+
existing["conflictDetail"][key] = [existing["properties"][key]]
|
|
224
|
+
existing["conflictDetail"][key].append(val)
|
|
225
|
+
existing["properties"].setdefault(key, val)
|
|
226
|
+
else:
|
|
227
|
+
seen[eid] = {
|
|
228
|
+
"id": eid,
|
|
229
|
+
"type": row.get("type", _inferType(ont)),
|
|
230
|
+
"properties": {k: v for k, v in row.items() if k not in ("id", "type")},
|
|
231
|
+
"sourceOntologies": [ont],
|
|
232
|
+
"conflict": False,
|
|
233
|
+
"conflictDetail": None,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
# Collect conflict entities
|
|
237
|
+
conflictList = [v for v in seen.values() if v["conflict"]]
|
|
238
|
+
|
|
239
|
+
return MergeResult(
|
|
240
|
+
results=list(seen.values()),
|
|
241
|
+
byOntology=results,
|
|
242
|
+
conflicts=conflictList,
|
|
243
|
+
failedOntologies=list(errors.keys()),
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _inferType(ontology: str) -> str:
|
|
248
|
+
"""Infer entity type from ontology name (aligned with ONTOLOGY §2.2 kind tags)."""
|
|
249
|
+
return {"episodic": "Event", "epistemic": "Point",
|
|
250
|
+
"semantic": "Entity", "docIndex": "Document"}.get(ontology, "unknown")
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _entityAnchoredCypher(entityId: str, ontologies: list[str]) -> dict[str, str]:
|
|
254
|
+
"""Generate entity-anchored Cypher overrides for each ontology.
|
|
255
|
+
|
|
256
|
+
Injects WHERE clause filtering to the given entityId into each ontology's
|
|
257
|
+
default Cypher template.
|
|
258
|
+
"""
|
|
259
|
+
import re
|
|
260
|
+
overrides: dict[str, str] = {}
|
|
261
|
+
for ont in ontologies:
|
|
262
|
+
base = ONTOLOGY_CYPHER.get(ont)
|
|
263
|
+
if not base:
|
|
264
|
+
continue
|
|
265
|
+
# Extract node variable from MATCH (var) or MATCH (var:Label)
|
|
266
|
+
m = re.match(r'MATCH\s*\((\w+)', base)
|
|
267
|
+
if m:
|
|
268
|
+
var = m.group(1)
|
|
269
|
+
cypher = base
|
|
270
|
+
if "WHERE" in cypher:
|
|
271
|
+
cypher = cypher.replace("WHERE ", f"WHERE {var}.id = $entityId AND ", 1)
|
|
272
|
+
elif "RETURN" in cypher:
|
|
273
|
+
cypher = cypher.replace("RETURN ", f"WHERE {var}.id = $entityId RETURN ", 1)
|
|
274
|
+
else:
|
|
275
|
+
cypher = cypher.replace(f"MATCH ({var}", f"MATCH ({var} {{id: $entityId}}")
|
|
276
|
+
overrides[ont] = cypher
|
|
277
|
+
return overrides
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
# ── Entry Point ───────────────────────────────────────
|
|
281
|
+
|
|
282
|
+
def crossOntologyQuery(
|
|
283
|
+
query: str,
|
|
284
|
+
db: Any, # raw FalkorDB client (NOT FalkorProjection — callers pass projection.db)
|
|
285
|
+
patterns: list[str] | None = None,
|
|
286
|
+
timeout: float = 5.0,
|
|
287
|
+
entityId: str | None = None,
|
|
288
|
+
) -> MergeResult:
|
|
289
|
+
"""Agent-facing entry point: NL query → integrated result.
|
|
290
|
+
|
|
291
|
+
Modes:
|
|
292
|
+
- NL mode (default): query → translateNL → route → dispatch
|
|
293
|
+
- Structured mode: patterns provided → skips translateNL, routes directly
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
query: Natural language query (e.g. "what decisions about competitor X?")
|
|
297
|
+
db: Raw FalkorDB client (NOT FalkorProjection wrapper)
|
|
298
|
+
patterns: Optional explicit patterns (bypasses translateNL when provided)
|
|
299
|
+
timeout: Per-ontology timeout in seconds
|
|
300
|
+
entityId: Optional entity ID — when provided, injects WHERE clause
|
|
301
|
+
filtering each sub-query to this entity (backward compatible)
|
|
302
|
+
|
|
303
|
+
Returns:
|
|
304
|
+
MergeResult with provenance-tagged, deduplicated results.
|
|
305
|
+
"""
|
|
306
|
+
if patterns is None:
|
|
307
|
+
patterns, _ = translateNL(query)
|
|
308
|
+
|
|
309
|
+
if not patterns:
|
|
310
|
+
# Unrecognised NL queries default to epistemic ("beliefs" pattern).
|
|
311
|
+
# ponytail: return empty MergeResult instead when consumers need
|
|
312
|
+
# to distinguish "no match" from "no data".
|
|
313
|
+
patterns = ["beliefs"]
|
|
314
|
+
|
|
315
|
+
ontologies = routeRead(patterns)
|
|
316
|
+
if not ontologies:
|
|
317
|
+
ontologies = ["epistemic"]
|
|
318
|
+
|
|
319
|
+
cypherOverrides: dict[str, str] | None = None
|
|
320
|
+
cypherParams: dict | None = None
|
|
321
|
+
if entityId:
|
|
322
|
+
cypherOverrides = _entityAnchoredCypher(entityId, ontologies)
|
|
323
|
+
cypherParams = {"entityId": entityId}
|
|
324
|
+
results, errors = dispatch(ontologies, db, timeout=timeout,
|
|
325
|
+
cypherOverrides=cypherOverrides,
|
|
326
|
+
cypherParams=cypherParams)
|
|
327
|
+
return merge(results, errors)
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
# ── DomainRouter — dynamic orchestrator for N ontologies ──
|
|
331
|
+
|
|
332
|
+
class DomainRouter:
|
|
333
|
+
"""Wraps base 4-ontology routing with domain extension routing.
|
|
334
|
+
|
|
335
|
+
Domain ontologies register query patterns + event types via the
|
|
336
|
+
domain manifest (config/domain_manifest.yaml, loaded by domain_loader).
|
|
337
|
+
Domain routing is merged with base routing — domain queries route to
|
|
338
|
+
domain ontologies, unrecognised patterns fall back to base routing.
|
|
339
|
+
|
|
340
|
+
Usage:
|
|
341
|
+
router = DomainRouter() # auto-loads manifest
|
|
342
|
+
router = DomainRouter(domains={...}) # explicit config
|
|
343
|
+
result = router.crossDomainQuery(
|
|
344
|
+
["product-strategy"], "show me all JTBD", db
|
|
345
|
+
)
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
def __init__(self, manifest_path: str | None = None,
|
|
349
|
+
domains: dict[str, "DomainRoutingConfig"] | None = None):
|
|
350
|
+
# Base routing tables (always present)
|
|
351
|
+
self._write_routing: dict[str, list[str]] = dict(ROUTING_TABLE_WRITE)
|
|
352
|
+
self._read_routing: dict[str, list[str]] = dict(ROUTING_TABLE_READ)
|
|
353
|
+
self._cypher_templates: dict[str, str] = dict(ONTOLOGY_CYPHER)
|
|
354
|
+
self._timeouts: dict[str, float] = {}
|
|
355
|
+
self._priorities: dict[str, int] = {}
|
|
356
|
+
|
|
357
|
+
# Load domain config
|
|
358
|
+
if domains is None and manifest_path is not None:
|
|
359
|
+
from tortoise.domain_loader import load_manifest
|
|
360
|
+
domains = load_manifest(manifest_path)
|
|
361
|
+
elif domains is None:
|
|
362
|
+
from tortoise.domain_loader import load_manifest
|
|
363
|
+
domains = load_manifest() # default path
|
|
364
|
+
|
|
365
|
+
for key, cfg in (domains or {}).items():
|
|
366
|
+
self.register_domain(key, cfg)
|
|
367
|
+
|
|
368
|
+
def register_domain(self, key: str, cfg: "DomainRoutingConfig") -> None:
|
|
369
|
+
"""Register a domain ontology's routing configuration.
|
|
370
|
+
|
|
371
|
+
Merges domain event types, query patterns, Cypher templates,
|
|
372
|
+
timeouts, and priorities into the router.
|
|
373
|
+
"""
|
|
374
|
+
# Write-side: event types → domain
|
|
375
|
+
self._write_routing[key] = list(cfg.event_types)
|
|
376
|
+
|
|
377
|
+
# Read-side: each query pattern maps to this domain
|
|
378
|
+
for pattern in cfg.query_patterns:
|
|
379
|
+
if pattern in self._read_routing:
|
|
380
|
+
self._read_routing[pattern].append(key)
|
|
381
|
+
else:
|
|
382
|
+
self._read_routing[pattern] = [key]
|
|
383
|
+
|
|
384
|
+
# Cypher template
|
|
385
|
+
if cfg.cypher_template:
|
|
386
|
+
self._cypher_templates[key] = cfg.cypher_template
|
|
387
|
+
|
|
388
|
+
# Per-domain config
|
|
389
|
+
if cfg.timeout:
|
|
390
|
+
self._timeouts[key] = cfg.timeout
|
|
391
|
+
if cfg.priority:
|
|
392
|
+
self._priorities[key] = cfg.priority
|
|
393
|
+
|
|
394
|
+
# ── Routing (merged base + domain) ────────────────
|
|
395
|
+
|
|
396
|
+
def routeWrite(self, eventType: str) -> list[str]:
|
|
397
|
+
"""Return ontologies (base + domain) that handle this event type."""
|
|
398
|
+
return [ont for ont, types in self._write_routing.items() if eventType in types]
|
|
399
|
+
|
|
400
|
+
def routeRead(self, patterns: list[str]) -> list[str]:
|
|
401
|
+
"""Return deduplicated union of ontologies for multiple patterns."""
|
|
402
|
+
ontologies: set[str] = set()
|
|
403
|
+
for p in patterns:
|
|
404
|
+
ontologies.update(self._read_routing.get(p, []))
|
|
405
|
+
return sorted(ontologies, key=lambda o: self._priorities.get(o, 10))
|
|
406
|
+
|
|
407
|
+
# ── Domain-specific query ─────────────────────────
|
|
408
|
+
|
|
409
|
+
def crossDomainQuery(
|
|
410
|
+
self,
|
|
411
|
+
domains: list[str],
|
|
412
|
+
query: str,
|
|
413
|
+
db: Any,
|
|
414
|
+
timeout: float | None = None,
|
|
415
|
+
) -> MergeResult:
|
|
416
|
+
"""Query one or more domain ontologies directly.
|
|
417
|
+
|
|
418
|
+
Routes to domain-specific Cypher templates, bypassing NL translation.
|
|
419
|
+
Unknown domains are silently skipped.
|
|
420
|
+
|
|
421
|
+
Args:
|
|
422
|
+
domains: Domain keys (e.g. ["product-strategy"])
|
|
423
|
+
query: NL query (unused for dispatch; future: filter injection)
|
|
424
|
+
db: FalkorDB client
|
|
425
|
+
timeout: Per-ontology timeout (overrides per-domain config)
|
|
426
|
+
|
|
427
|
+
Returns:
|
|
428
|
+
MergeResult with domain-ontology results.
|
|
429
|
+
"""
|
|
430
|
+
known = [d for d in domains if d in self._cypher_templates]
|
|
431
|
+
if not known:
|
|
432
|
+
return MergeResult()
|
|
433
|
+
|
|
434
|
+
timeout_per = timeout or max(
|
|
435
|
+
(self._timeouts.get(d, 5.0) for d in known), default=5.0
|
|
436
|
+
)
|
|
437
|
+
results, errors = dispatch(known, db, timeout=timeout_per,
|
|
438
|
+
cypherOverrides=self._cypher_templates)
|
|
439
|
+
return merge(results, errors)
|
|
440
|
+
|
|
441
|
+
# ── Full cross-ontology query (base + domain) ─────
|
|
442
|
+
|
|
443
|
+
def crossOntologyQuery(
|
|
444
|
+
self,
|
|
445
|
+
query: str,
|
|
446
|
+
db: Any,
|
|
447
|
+
patterns: list[str] | None = None,
|
|
448
|
+
timeout: float = 5.0,
|
|
449
|
+
entityId: str | None = None,
|
|
450
|
+
) -> MergeResult:
|
|
451
|
+
"""Agent-facing entry point: NL query → integrated result.
|
|
452
|
+
|
|
453
|
+
Uses merged (base + domain) routing. Same semantics as the
|
|
454
|
+
module-level crossOntologyQuery(), but with domain routing merged in.
|
|
455
|
+
"""
|
|
456
|
+
if patterns is None:
|
|
457
|
+
patterns, _ = translateNL(query)
|
|
458
|
+
|
|
459
|
+
if not patterns:
|
|
460
|
+
patterns = ["beliefs"]
|
|
461
|
+
|
|
462
|
+
ontologies = self.routeRead(patterns)
|
|
463
|
+
if not ontologies:
|
|
464
|
+
ontologies = ["epistemic"]
|
|
465
|
+
|
|
466
|
+
cypherOverrides: dict[str, str] | None = None
|
|
467
|
+
cypherParams: dict | None = None
|
|
468
|
+
if entityId:
|
|
469
|
+
cypherOverrides = _entityAnchoredCypher(entityId, ontologies)
|
|
470
|
+
cypherParams = {"entityId": entityId}
|
|
471
|
+
results, errors = dispatch(ontologies, db, timeout=timeout,
|
|
472
|
+
cypherOverrides={**self._cypher_templates,
|
|
473
|
+
**(cypherOverrides or {})},
|
|
474
|
+
cypherParams=cypherParams)
|
|
475
|
+
return merge(results, errors)
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
# ── Module-level crossDomainQuery (convenience) ───────
|
|
479
|
+
|
|
480
|
+
def crossDomainQuery(
|
|
481
|
+
domains: list[str],
|
|
482
|
+
query: str,
|
|
483
|
+
db: Any,
|
|
484
|
+
timeout: float | None = None,
|
|
485
|
+
) -> MergeResult:
|
|
486
|
+
"""Query domain ontologies directly (without full NL routing).
|
|
487
|
+
|
|
488
|
+
Convenience wrapper that creates a DomainRouter and dispatches.
|
|
489
|
+
For repeated use, instantiate DomainRouter directly.
|
|
490
|
+
"""
|
|
491
|
+
router = DomainRouter()
|
|
492
|
+
return router.crossDomainQuery(domains, query, db, timeout=timeout)
|
tortoise/memory_scope.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from typing import Protocol, runtime_checkable, Any
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@runtime_checkable
|
|
5
|
+
class MemoryScope(Protocol):
|
|
6
|
+
"""Storage-agnostic memory scoping interface. ARCH-002, PROV-F-009."""
|
|
7
|
+
managed_by: str
|
|
8
|
+
owned_by: str
|
|
9
|
+
|
|
10
|
+
def filter(self, team_id: str, memory_types: list[str]) -> dict[str, Any]:
|
|
11
|
+
"""Return filtered context scoped to team and memory types.
|
|
12
|
+
|
|
13
|
+
Backend adapters implement this: FalkorDB today, replaceable tomorrow.
|
|
14
|
+
"""
|
|
15
|
+
...
|