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
tortoise/analyze.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
1
|
+
"""tortoise_analyze — template-based NL→Cypher graph analysis.
|
|
2
|
+
|
|
3
|
+
Single MCP tool: tortoise_analyze(question) → natural language answer.
|
|
4
|
+
Template Cypher + LLM for intent classification and result synthesis.
|
|
5
|
+
No LLM-Cypher generation (rejected: 61% accuracy, 40% silent errors).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json, os, re
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
14
|
+
# Template Registry
|
|
15
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
16
|
+
|
|
17
|
+
TEMPLATES: dict[str, dict] = {
|
|
18
|
+
"disagreement": {
|
|
19
|
+
"triggers": ["disagree", "conflict", "oppose", "contradict", "tension", "contested"],
|
|
20
|
+
"description": "Find NAND conflicts between high-confidence claims",
|
|
21
|
+
"subgraph_vars": ["a", "b"],
|
|
22
|
+
"cypher": """
|
|
23
|
+
MATCH (a:Point)<-[:NAND]-(op:Point {op_type:\"NAND\"})-[:NAND]->(b:Point)
|
|
24
|
+
WHERE a.id <> b.id
|
|
25
|
+
AND (a.is_operator IS NULL OR a.is_operator = false)
|
|
26
|
+
AND (b.is_operator IS NULL OR b.is_operator = false)
|
|
27
|
+
AND coalesce(a.confidence, 0.5) > 0.45
|
|
28
|
+
AND coalesce(b.confidence, 0.5) > 0.45
|
|
29
|
+
RETURN a.id, a.content, coalesce(a.confidence,0.5) as a_conf,
|
|
30
|
+
b.id, b.content, coalesce(b.confidence,0.5) as b_conf
|
|
31
|
+
ORDER BY a_conf DESC LIMIT $limit
|
|
32
|
+
""",
|
|
33
|
+
"format": lambda rows: _format_pairs(rows, "conflict"),
|
|
34
|
+
},
|
|
35
|
+
"strongest_for": {
|
|
36
|
+
"triggers": ["strongest", "best argument", "most support", "evidence for", "supports"],
|
|
37
|
+
"description": "Find claims supporting a target via IMPL chains, ranked by confidence",
|
|
38
|
+
"subgraph_vars": ["supporter"],
|
|
39
|
+
"cypher": """
|
|
40
|
+
MATCH (supporter:Point)<-[:IMPL]-(op:Point {op_type:\"IMPL\"})-[:IMPL]->(target:Point)
|
|
41
|
+
WHERE target.id <> supporter.id
|
|
42
|
+
AND target.content CONTAINS $entity
|
|
43
|
+
AND coalesce(supporter.confidence, 0.5) > 0.0
|
|
44
|
+
RETURN supporter.id, supporter.content, coalesce(supporter.confidence,0.5) as conf
|
|
45
|
+
ORDER BY conf DESC LIMIT $limit
|
|
46
|
+
""",
|
|
47
|
+
"format": lambda rows: _format_ranked(rows, "supporting"),
|
|
48
|
+
},
|
|
49
|
+
"counter_arguments": {
|
|
50
|
+
"triggers": ["counter", "against", "objection", "contradicts", "opposes", "attack"],
|
|
51
|
+
"description": "Find claims that contradict a target via NAND edges",
|
|
52
|
+
"subgraph_vars": ["opponent"],
|
|
53
|
+
"cypher": """
|
|
54
|
+
MATCH (target:Point)<-[:NAND]-(op:Point {op_type:\"NAND\"})-[:NAND]->(opponent:Point)
|
|
55
|
+
WHERE target.id <> opponent.id
|
|
56
|
+
AND target.content CONTAINS $entity
|
|
57
|
+
AND (opponent.is_operator IS NULL OR opponent.is_operator = false)
|
|
58
|
+
RETURN opponent.id, opponent.content, coalesce(opponent.confidence,0.5) as conf
|
|
59
|
+
ORDER BY conf DESC LIMIT $limit
|
|
60
|
+
""",
|
|
61
|
+
"format": lambda rows: _format_ranked(rows, "counter"),
|
|
62
|
+
},
|
|
63
|
+
"consensus": {
|
|
64
|
+
"triggers": ["consensus", "agree", "shared", "common ground", "everyone believes"],
|
|
65
|
+
"description": "Find high-confidence claims with no NAND attacks (consensus)",
|
|
66
|
+
"subgraph_vars": ["c"],
|
|
67
|
+
"cypher": """
|
|
68
|
+
MATCH (c:Point)
|
|
69
|
+
WHERE (c.is_operator IS NULL OR c.is_operator = false)
|
|
70
|
+
AND coalesce(c.confidence, 0.5) > 0.6
|
|
71
|
+
AND NOT (c)<-[:NAND]-(:Point {op_type:\"NAND\"})
|
|
72
|
+
RETURN c.id, c.content, coalesce(c.confidence,0.5) as conf
|
|
73
|
+
ORDER BY conf DESC LIMIT $limit
|
|
74
|
+
""",
|
|
75
|
+
"format": lambda rows: _format_ranked(rows, "consensus"),
|
|
76
|
+
},
|
|
77
|
+
"most_uncertain": {
|
|
78
|
+
"triggers": ["uncertain", "weakest", "least sure", "unknown", "unsure", "low confidence"],
|
|
79
|
+
"description": "Find claims with lowest EP confidence or highest variance",
|
|
80
|
+
"subgraph_vars": ["c"],
|
|
81
|
+
"cypher": """
|
|
82
|
+
MATCH (c:Point)
|
|
83
|
+
WHERE (c.is_operator IS NULL OR c.is_operator = false)
|
|
84
|
+
AND c.ep_alpha IS NOT NULL AND c.ep_beta IS NOT NULL
|
|
85
|
+
WITH c, (c.ep_alpha * c.ep_beta) /
|
|
86
|
+
((c.ep_alpha + c.ep_beta)^2 * (c.ep_alpha + c.ep_beta + 1)) as variance
|
|
87
|
+
RETURN c.id, c.content, coalesce(c.confidence,0.5) as conf, variance
|
|
88
|
+
ORDER BY variance DESC LIMIT $limit
|
|
89
|
+
""",
|
|
90
|
+
"format": lambda rows: _format_uncertain(rows),
|
|
91
|
+
},
|
|
92
|
+
"evidence_chain": {
|
|
93
|
+
"triggers": ["evidence for", "supports", "basis", "foundation", "backing", "chain"],
|
|
94
|
+
"description": "Trace IMPL support chain back to root evidence for a claim",
|
|
95
|
+
"subgraph_vars": ["evidence"],
|
|
96
|
+
"cypher": """
|
|
97
|
+
MATCH (evidence:Point)<-[:IMPL]-(op:Point {op_type:\"IMPL\"})-[:IMPL]->(target:Point)
|
|
98
|
+
WHERE target.id <> evidence.id
|
|
99
|
+
AND target.content CONTAINS $entity
|
|
100
|
+
AND (evidence.is_operator IS NULL OR evidence.is_operator = false)
|
|
101
|
+
RETURN evidence.id, evidence.content, coalesce(evidence.confidence,0.5) as conf
|
|
102
|
+
ORDER BY conf DESC LIMIT $limit
|
|
103
|
+
""",
|
|
104
|
+
"format": lambda rows: _format_chain(rows),
|
|
105
|
+
},
|
|
106
|
+
"trends": {
|
|
107
|
+
"triggers": ["changed", "trend", "evolved", "over time", "history", "how has"],
|
|
108
|
+
"description": "Show confidence changes by comparing node properties over time",
|
|
109
|
+
"subgraph_vars": ["c"],
|
|
110
|
+
"cypher": """
|
|
111
|
+
MATCH (c:Point)
|
|
112
|
+
WHERE c.content CONTAINS $entity
|
|
113
|
+
AND c.ep_alpha IS NOT NULL
|
|
114
|
+
RETURN c.id, c.content, coalesce(c.confidence,0.5) as conf,
|
|
115
|
+
c.ep_alpha, c.ep_beta, c.createdAt
|
|
116
|
+
ORDER BY c.createdAt DESC LIMIT $limit
|
|
117
|
+
""",
|
|
118
|
+
"format": lambda rows: _format_timeline(rows),
|
|
119
|
+
},
|
|
120
|
+
"grounding": {
|
|
121
|
+
"triggers": ["grounded", "central", "important", "key", "pivotal", "core"],
|
|
122
|
+
"description": "Find most central claims by PageRank grounding score",
|
|
123
|
+
"subgraph_vars": ["c"],
|
|
124
|
+
"cypher": """
|
|
125
|
+
MATCH (c:Point)
|
|
126
|
+
WHERE (c.is_operator IS NULL OR c.is_operator = false)
|
|
127
|
+
AND c.grounding IS NOT NULL
|
|
128
|
+
RETURN c.id, c.content, c.grounding
|
|
129
|
+
ORDER BY c.grounding DESC LIMIT $limit
|
|
130
|
+
""",
|
|
131
|
+
"format": lambda rows: _format_ranked(rows, "grounding"),
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
137
|
+
# Formatters
|
|
138
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
139
|
+
|
|
140
|
+
def _format_pairs(rows: list, label: str) -> str:
|
|
141
|
+
if not rows:
|
|
142
|
+
return f"No {label}s found."
|
|
143
|
+
lines = [f"{len(rows)} {label}(s) found:"]
|
|
144
|
+
for r in rows[:10]:
|
|
145
|
+
lines.append(f" • \"{r[1][:80]}\" ({r[2]:.2f}) ⇎ \"{r[4][:80]}\" ({r[5]:.2f})")
|
|
146
|
+
return "\n".join(lines)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _format_ranked(rows: list, label: str) -> str:
|
|
150
|
+
if not rows:
|
|
151
|
+
return f"No {label} claims found."
|
|
152
|
+
lines = [f"Top {label} claims:"]
|
|
153
|
+
for i, r in enumerate(rows[:10], 1):
|
|
154
|
+
conf = r[2] if len(r) > 2 else r[2] if len(r) > 2 else "?"
|
|
155
|
+
lines.append(f" {i}. \"{r[1][:80]}\" (confidence: {float(conf):.2f})")
|
|
156
|
+
return "\n".join(lines)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _format_uncertain(rows: list) -> str:
|
|
160
|
+
if not rows:
|
|
161
|
+
return "No uncertain claims found."
|
|
162
|
+
lines = ["Most uncertain claims (highest variance):"]
|
|
163
|
+
for i, r in enumerate(rows[:10], 1):
|
|
164
|
+
lines.append(f" {i}. \"{r[1][:80]}\" (conf: {r[2]:.2f}, var: {r[3]:.4f})")
|
|
165
|
+
return "\n".join(lines)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _format_chain(rows: list) -> str:
|
|
169
|
+
if not rows:
|
|
170
|
+
return "No evidence chain found."
|
|
171
|
+
lines = ["Evidence chain (ordered by proximity):"]
|
|
172
|
+
for r in rows[:10]:
|
|
173
|
+
lines.append(f" [{r[3]} hops] \"{r[1][:80]}\" (conf: {r[2]:.2f})")
|
|
174
|
+
return "\n".join(lines)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _format_timeline(rows: list) -> str:
|
|
178
|
+
if not rows:
|
|
179
|
+
return "No timeline data found."
|
|
180
|
+
lines = ["Confidence timeline:"]
|
|
181
|
+
for r in rows[:10]:
|
|
182
|
+
ts = r[5][:10] if len(r) > 5 and r[5] else "?"
|
|
183
|
+
lines.append(f" [{ts}] \"{r[1][:80]}\" (α={r[3]:.1f}, β={r[4]:.1f}, conf={r[2]:.2f})")
|
|
184
|
+
return "\n".join(lines)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
188
|
+
# Classification
|
|
189
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
190
|
+
|
|
191
|
+
def classify(question: str) -> tuple[str, dict] | None:
|
|
192
|
+
"""Keyword match question to template pattern. Returns (name, params) or None."""
|
|
193
|
+
q = question.lower()
|
|
194
|
+
for name, tmpl in TEMPLATES.items():
|
|
195
|
+
for trigger in tmpl["triggers"]:
|
|
196
|
+
if trigger in q:
|
|
197
|
+
# Extract entity parameter
|
|
198
|
+
entity = _extract_entity(q, trigger)
|
|
199
|
+
return name, {"entity": entity, "limit": 20}
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _extract_entity(question: str, trigger: str) -> str:
|
|
204
|
+
"""Extract entity name from question by removing trigger words and common phrases."""
|
|
205
|
+
# Simple heuristic: remove the trigger and common surrounding words
|
|
206
|
+
q = question.lower()
|
|
207
|
+
# Remove common phrases
|
|
208
|
+
for phrase in ["what is the", "what are the", "show me", "find", "tell me about",
|
|
209
|
+
"what claims", "which claims", "where is the", "how has"]:
|
|
210
|
+
q = q.replace(phrase, "")
|
|
211
|
+
# Remove the trigger word
|
|
212
|
+
q = q.replace(trigger, "")
|
|
213
|
+
# Remove common connector words
|
|
214
|
+
for word in ["about", "for", "of", "the", "in", "on", "to", "that", "is", "are"]:
|
|
215
|
+
q = re.sub(rf'\b{word}\b', '', q)
|
|
216
|
+
# Clean up
|
|
217
|
+
entity = ' '.join(q.split()).strip()
|
|
218
|
+
return entity if entity else ""
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
222
|
+
# LLM Integration (optional — keyword match handles 80% of queries)
|
|
223
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
224
|
+
|
|
225
|
+
# #329: provider-key pairing — a key is ONLY ever sent to the provider that
|
|
226
|
+
# issued it. (The old code used `OPENAI_API_KEY or DEEPSEEK_API_KEY` and always
|
|
227
|
+
# POSTed to api.deepseek.com — the OpenAI key was exfiltrated to DeepSeek.)
|
|
228
|
+
_LLM_PROVIDERS: dict[str, tuple[str, str]] = {
|
|
229
|
+
"DEEPSEEK_API_KEY": ("https://api.deepseek.com/v1/chat/completions", "deepseek-chat"),
|
|
230
|
+
"OPENAI_API_KEY": ("https://api.openai.com/v1/chat/completions", "gpt-4o-mini"),
|
|
231
|
+
}
|
|
232
|
+
# Priority order when multiple keys are set (deepseek first — historical default).
|
|
233
|
+
_LLM_PROVIDER_PRIORITY: tuple[str, ...] = ("DEEPSEEK_API_KEY", "OPENAI_API_KEY")
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def llm_classify(question: str) -> tuple[str, dict] | None:
|
|
237
|
+
"""Use LLM to classify intent + extract params when keyword match fails.
|
|
238
|
+
|
|
239
|
+
#329: picks the provider whose OWN env key is set; an empty-string key is
|
|
240
|
+
treated as unset. The chosen key is only sent to its own provider's URL.
|
|
241
|
+
Returns None (keyword-only fallback) when no key is set or the provider
|
|
242
|
+
request fails — a provider outage never falls through to another provider
|
|
243
|
+
(that would leak the wrong key too).
|
|
244
|
+
"""
|
|
245
|
+
import urllib.request
|
|
246
|
+
api_key = None
|
|
247
|
+
provider_url = None
|
|
248
|
+
provider_model = None
|
|
249
|
+
for env_name in _LLM_PROVIDER_PRIORITY:
|
|
250
|
+
candidate = os.environ.get(env_name)
|
|
251
|
+
if candidate: # non-empty string
|
|
252
|
+
api_key, (provider_url, provider_model) = candidate, _LLM_PROVIDERS[env_name]
|
|
253
|
+
break
|
|
254
|
+
if api_key is None:
|
|
255
|
+
return None # fall back to keyword only
|
|
256
|
+
|
|
257
|
+
try:
|
|
258
|
+
body = json.dumps({
|
|
259
|
+
"model": provider_model,
|
|
260
|
+
"temperature": 0,
|
|
261
|
+
"response_format": {"type": "json_object"},
|
|
262
|
+
"messages": [{"role": "system", "content": LLM_PROMPT},
|
|
263
|
+
{"role": "user", "content": question}],
|
|
264
|
+
}).encode()
|
|
265
|
+
req = urllib.request.Request(
|
|
266
|
+
provider_url,
|
|
267
|
+
data=body,
|
|
268
|
+
headers={"Content-Type": "application/json",
|
|
269
|
+
"Authorization": f"Bearer {api_key}"},
|
|
270
|
+
)
|
|
271
|
+
with urllib.request.urlopen(req, timeout=10) as r:
|
|
272
|
+
data = json.loads(r.read())
|
|
273
|
+
result = json.loads(data["choices"][0]["message"]["content"])
|
|
274
|
+
return result.get("pattern"), result.get("params", {})
|
|
275
|
+
except Exception:
|
|
276
|
+
return None
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
LLM_PROMPT = """You classify questions about an epistemic graph. Output JSON:
|
|
280
|
+
{"pattern": "<name>", "params": {"entity": "...", "limit": 20}}
|
|
281
|
+
|
|
282
|
+
Available patterns:
|
|
283
|
+
- disagreement: "where is the disagreement/conflict?"
|
|
284
|
+
- strongest_for: "what supports/strongest evidence for X?"
|
|
285
|
+
- counter_arguments: "what contradicts/attacks X?"
|
|
286
|
+
- consensus: "what do we agree on?"
|
|
287
|
+
- most_uncertain: "what are we least sure about?"
|
|
288
|
+
- evidence_chain: "trace the evidence for X"
|
|
289
|
+
- trends: "how has X changed over time?"
|
|
290
|
+
- grounding: "what are the most central/important claims?"
|
|
291
|
+
|
|
292
|
+
Only output JSON. No other text."""
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
296
|
+
# Subgraph Filter Injection
|
|
297
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
298
|
+
|
|
299
|
+
def _inject_subgraph_filter(cypher: str, vars: list[str],
|
|
300
|
+
ids: set[str]) -> str:
|
|
301
|
+
"""Inject ID filter into Cypher WHERE clause for entity-scoped analysis."""
|
|
302
|
+
if not vars:
|
|
303
|
+
return cypher
|
|
304
|
+
id_list = json.dumps(list(ids))
|
|
305
|
+
filters = ' AND '.join(f'{v}.id IN {id_list}' for v in vars)
|
|
306
|
+
return cypher.replace('WHERE ', f'WHERE {filters} AND ', 1)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
310
|
+
# Main API
|
|
311
|
+
# ═══════════════════════════════════════════════════════════════════
|
|
312
|
+
|
|
313
|
+
def _bfs_select_operators(proj, anchors: list[str], max_hops: int = 1,
|
|
314
|
+
rel_filter: str = "IMPL|NAND",
|
|
315
|
+
direction: str = "both") -> set[str]:
|
|
316
|
+
"""BFS subgraph selection from anchor Points — returns set of operator Point IDs.
|
|
317
|
+
|
|
318
|
+
Shared helper for both compute_confidence and tortoise_analyze.
|
|
319
|
+
Expands from anchor Points along operator edges (IMPL|NAND) for max_hops hops.
|
|
320
|
+
IMPL edges respect direction; NAND always traversed bidirectionally.
|
|
321
|
+
Capped at 200 operator IDs.
|
|
322
|
+
"""
|
|
323
|
+
import logging
|
|
324
|
+
_log = logging.getLogger(__name__)
|
|
325
|
+
collected: set[str] = set()
|
|
326
|
+
frontier: set[str] = set(anchors)
|
|
327
|
+
visited: set[str] = set(anchors)
|
|
328
|
+
rel_types = set(rel_filter.split("|"))
|
|
329
|
+
|
|
330
|
+
for hop in range(max_hops):
|
|
331
|
+
if not frontier:
|
|
332
|
+
break
|
|
333
|
+
new_ops: set[str] = set()
|
|
334
|
+
new_points: set[str] = set()
|
|
335
|
+
frontier_list = list(frontier)
|
|
336
|
+
|
|
337
|
+
for rel in rel_types:
|
|
338
|
+
if rel not in ("IMPL", "NAND"):
|
|
339
|
+
continue
|
|
340
|
+
|
|
341
|
+
# NAND is always bidirectional; IMPL respects direction flag
|
|
342
|
+
if rel == "NAND":
|
|
343
|
+
dirs = ("incoming", "outgoing")
|
|
344
|
+
elif direction == "both":
|
|
345
|
+
dirs = ("incoming", "outgoing")
|
|
346
|
+
else:
|
|
347
|
+
dirs = (direction,)
|
|
348
|
+
|
|
349
|
+
for d in dirs:
|
|
350
|
+
if d == "incoming":
|
|
351
|
+
rows = proj.g.query(
|
|
352
|
+
f"MATCH (op:Point {{is_operator:true}})-[:{rel}]->(p:Point) "
|
|
353
|
+
"WHERE p.id IN $frontier "
|
|
354
|
+
"RETURN DISTINCT op.id",
|
|
355
|
+
params={"frontier": frontier_list},
|
|
356
|
+
).result_set
|
|
357
|
+
for (op_id,) in rows:
|
|
358
|
+
new_ops.add(op_id)
|
|
359
|
+
new_points.add(op_id)
|
|
360
|
+
else: # outgoing
|
|
361
|
+
rows = proj.g.query(
|
|
362
|
+
f"MATCH (op:Point {{is_operator:true}})-[:{rel}]->(target:Point) "
|
|
363
|
+
"WHERE op.id IN $frontier "
|
|
364
|
+
"RETURN DISTINCT target.id",
|
|
365
|
+
params={"frontier": frontier_list},
|
|
366
|
+
).result_set
|
|
367
|
+
for (target_id,) in rows:
|
|
368
|
+
new_points.add(target_id)
|
|
369
|
+
|
|
370
|
+
collected |= new_ops
|
|
371
|
+
|
|
372
|
+
if len(collected) > 200:
|
|
373
|
+
_log.warning(
|
|
374
|
+
"BFS selector: collected %d operators, truncating to 200.",
|
|
375
|
+
len(collected),
|
|
376
|
+
)
|
|
377
|
+
# Deterministic truncation — set iteration order is non-deterministic
|
|
378
|
+
# (hash randomization); sort by ID for reproducible selection.
|
|
379
|
+
collected = set(sorted(collected)[:200])
|
|
380
|
+
break
|
|
381
|
+
|
|
382
|
+
# Expand to new frontier points from collected operators
|
|
383
|
+
if new_ops and hop < max_hops - 1:
|
|
384
|
+
ops_list = list(new_ops)
|
|
385
|
+
rows = proj.g.query(
|
|
386
|
+
"MATCH (op:Point {is_operator:true})-[r:IMPL|NAND]->(p:Point) "
|
|
387
|
+
"WHERE op.id IN $ops "
|
|
388
|
+
"RETURN DISTINCT p.id",
|
|
389
|
+
params={"ops": ops_list},
|
|
390
|
+
).result_set
|
|
391
|
+
for (p_id,) in rows:
|
|
392
|
+
if p_id not in visited:
|
|
393
|
+
new_points.add(p_id)
|
|
394
|
+
|
|
395
|
+
frontier = new_points - visited
|
|
396
|
+
visited |= new_points
|
|
397
|
+
|
|
398
|
+
return collected
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def analyze(question: str, proj=None, *,
|
|
402
|
+
entity_subgraph_ids: set[str] | None = None,
|
|
403
|
+
anchor_ids: list[str] | None = None,
|
|
404
|
+
max_hops: int = 1,
|
|
405
|
+
rel_filter: str = "IMPL|NAND",
|
|
406
|
+
direction: str = "both",
|
|
407
|
+
use_llm: bool = True) -> dict[str, Any]:
|
|
408
|
+
"""Answer a natural language question about the Tortoise graph.
|
|
409
|
+
|
|
410
|
+
Args:
|
|
411
|
+
question: Natural language question
|
|
412
|
+
proj: FalkorProjection instance (optional — for Cypher execution)
|
|
413
|
+
entity_subgraph_ids: Pre-filter results to these Point IDs (entity-scoped analysis)
|
|
414
|
+
anchor_ids: list of Point IDs for BFS subgraph selection (new; alternative to entity_subgraph_ids)
|
|
415
|
+
anchor_ids: list of Point IDs for BFS subgraph selection (new; alternative to entity_subgraph_ids)
|
|
416
|
+
max_hops: BFS expansion depth when using anchor_ids (default 1)
|
|
417
|
+
rel_filter: edge types for BFS — "IMPL", "NAND", or "IMPL|NAND" (default)
|
|
418
|
+
direction: IMPL edge traversal direction — "incoming", "outgoing", or "both" (default)
|
|
419
|
+
use_llm: Fall back to LLM if keyword match fails
|
|
420
|
+
|
|
421
|
+
Returns:
|
|
422
|
+
{"answer": "...", "raw": [...], "pattern": "...", "query": "..."}
|
|
423
|
+
"""
|
|
424
|
+
# BFS subgraph selection from anchor IDs
|
|
425
|
+
if anchor_ids is not None and proj is not None and entity_subgraph_ids is None:
|
|
426
|
+
entity_subgraph_ids = _bfs_select_operators(
|
|
427
|
+
proj, anchor_ids, max_hops=max_hops,
|
|
428
|
+
rel_filter=rel_filter, direction=direction,
|
|
429
|
+
)
|
|
430
|
+
# 1. Classify intent
|
|
431
|
+
result = classify(question)
|
|
432
|
+
if result is None and use_llm:
|
|
433
|
+
result = llm_classify(question)
|
|
434
|
+
if result is None:
|
|
435
|
+
return {"answer": "I couldn't understand that question. Try asking about: "
|
|
436
|
+
"disagreement, strongest claims, counter-arguments, consensus, "
|
|
437
|
+
"uncertainty, evidence chains, trends, or grounding.",
|
|
438
|
+
"raw": [], "pattern": None, "query": None}
|
|
439
|
+
|
|
440
|
+
pattern_name, params = result
|
|
441
|
+
tmpl = TEMPLATES.get(pattern_name)
|
|
442
|
+
if tmpl is None:
|
|
443
|
+
# #329: pattern_name comes from the LLM (untrusted) — never echo it raw
|
|
444
|
+
return {"answer": "Unknown pattern requested.", "raw": [], "pattern": None, "query": None}
|
|
445
|
+
|
|
446
|
+
# 2. Execute Cypher
|
|
447
|
+
cypher = tmpl["cypher"]
|
|
448
|
+
if entity_subgraph_ids is not None:
|
|
449
|
+
cypher = _inject_subgraph_filter(cypher, tmpl.get("subgraph_vars", []),
|
|
450
|
+
entity_subgraph_ids)
|
|
451
|
+
|
|
452
|
+
rows = []
|
|
453
|
+
if proj is not None:
|
|
454
|
+
try:
|
|
455
|
+
rows = proj.g.query(cypher, params=params).result_set
|
|
456
|
+
except Exception as e:
|
|
457
|
+
# #329: redact — tenants must not see raw DB errors or query text
|
|
458
|
+
from .security import redact_error
|
|
459
|
+
return {"answer": f"Query error: {redact_error(e)}", "raw": [], "pattern": pattern_name, "query": None}
|
|
460
|
+
|
|
461
|
+
# 3. Format
|
|
462
|
+
formatter = tmpl.get("format")
|
|
463
|
+
if formatter:
|
|
464
|
+
answer = formatter(rows)
|
|
465
|
+
else:
|
|
466
|
+
answer = f"Found {len(rows)} results."
|
|
467
|
+
|
|
468
|
+
return {
|
|
469
|
+
"answer": answer,
|
|
470
|
+
"raw": [[str(v) for v in row] for row in rows[:20]],
|
|
471
|
+
"pattern": pattern_name,
|
|
472
|
+
"query": cypher,
|
|
473
|
+
}
|