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/mining.py ADDED
@@ -0,0 +1,338 @@
1
+ """Conversation mining pipeline — transcript → Events + Points.
2
+
3
+ GAP-15 / #7003: Wire extractor.py Tier1/Tier2 → transcript → EventRecorded events.
4
+ Gate: ≥3 events/session (meeting + decision + friction/milestone).
5
+
6
+ Architecture (from plan WF4):
7
+ Conversation transcript → extractor (Points + Operators) →
8
+ Event derivation (meeting, decision, friction) → JSONL append → projection.apply()
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from datetime import datetime, timezone
14
+
15
+ from typing import Any
16
+
17
+ from .api import EventAPI
18
+ from .extractor import MockExtractor, LLMExtractor
19
+ from .ids import ulid, now_iso
20
+
21
+
22
+ def _now() -> str:
23
+ return datetime.now(timezone.utc).isoformat()
24
+
25
+
26
+ # Cue-word patterns for eventKind derivation
27
+ _DECISION_WORDS = (
28
+ "decided", "decide", "decision", "choose", "chosen", "chose",
29
+ "adopt", "adopted", "resolve", "resolved", "agree", "agreed",
30
+ "commit", "committed", "confirm", "finalize", "settle",
31
+ )
32
+ _FRICTION_WORDS = (
33
+ "disagree", "disagrees", "contradict", "contradiction",
34
+ "conflict", "dispute", "object", "objection", "push back",
35
+ "not agree", "wrong", "incorrect", "doesn't work",
36
+ )
37
+ _MILESTONE_WORDS = (
38
+ "discover", "discovered", "finding", "breakthrough",
39
+ "realize", "realized", "insight", "key learning",
40
+ "important", "significant", "critical finding",
41
+ )
42
+
43
+
44
+ class ConversationMiner:
45
+ """Mine conversation transcripts → Points + Operators + EventRecorded events.
46
+
47
+ Produces ≥3 EventRecorded events per session:
48
+ 1. One "meeting" event (the session itself)
49
+ 2. "decision" events when decision language is detected
50
+ 3. "friction" events for contradictions (NAND operators) and conflict language
51
+ 4. "milestone" events for significant findings (falls back if <3 total)
52
+ """
53
+
54
+ def __init__(self, model: Any = None):
55
+ # model: anything with .complete() — MockModel, OpenAICompatModel, etc.
56
+ self.model = model
57
+
58
+ def mine(
59
+ self,
60
+ transcript: str,
61
+ source_id: str,
62
+ api: EventAPI,
63
+ *,
64
+ participants: list[str] | None = None,
65
+ session_started_at: str | None = None,
66
+ ) -> dict:
67
+ """Run extraction pipeline on a conversation transcript.
68
+
69
+ Returns: {events: N, points: M, operators: K, event_ids: [...]}
70
+ """
71
+ started_at = session_started_at or _now()
72
+
73
+ # 1. Run extractor: Points + IMPL/NAND operators
74
+ extractor = self._make_extractor()
75
+ extractor.run(transcript, source_id, api)
76
+
77
+ # 2. Collect what was just produced by reading back from the log
78
+ points, operators = self._collect_recent(api)
79
+
80
+ # 3. Derive session-level EventRecorded events
81
+ events = self._derive_events(
82
+ transcript, source_id, points, operators,
83
+ participants=participants,
84
+ started_at=started_at,
85
+ )
86
+
87
+ # 4. Emit events via API log + projection
88
+ event_ids = []
89
+ for ev in events:
90
+ event_ids.append(ev["eventId"])
91
+ self._emit_event(api, ev)
92
+
93
+ return {
94
+ "events": len(events),
95
+ "points": len(points),
96
+ "operators": len(operators),
97
+ "event_ids": event_ids,
98
+ }
99
+
100
+ # ── Internal helpers ───────────────────────────────────────────
101
+
102
+ def _make_extractor(self):
103
+ if self.model is not None:
104
+ return LLMExtractor(self.model, self.model)
105
+ return MockExtractor()
106
+
107
+ def _collect_recent(self, api: EventAPI) -> tuple[list[dict], list[dict]]:
108
+ """Collect PointAdded and OperatorAdded events from the current run."""
109
+ run_id = getattr(api, "current_run", None)
110
+ points: list[dict] = []
111
+ operators: list[dict] = []
112
+ for ev in api.log.read_all():
113
+ if ev.get("type") == "PointAdded":
114
+ p = ev.get("point", {})
115
+ if run_id and p.get("provenance", {}).get("run_id") == run_id:
116
+ points.append(p)
117
+ elif not run_id:
118
+ points.append(p)
119
+ elif ev.get("type") == "OperatorAdded":
120
+ op = ev.get("point", {})
121
+ if run_id and op.get("provenance", {}).get("run_id") == run_id:
122
+ operators.append(op)
123
+ elif not run_id:
124
+ operators.append(op)
125
+ return points, operators
126
+
127
+ def _derive_events(
128
+ self,
129
+ transcript: str,
130
+ source_id: str,
131
+ points: list[dict],
132
+ operators: list[dict],
133
+ *,
134
+ participants: list[str] | None = None,
135
+ started_at: str | None = None,
136
+ ) -> list[dict]:
137
+ """Derive session-level EventRecorded events from extraction results."""
138
+ ts = started_at or _now()
139
+ source = f"conversation:{source_id}"
140
+ parts = participants or self._extract_participants(transcript)
141
+
142
+ events: list[dict] = []
143
+
144
+ # Event 1: The meeting itself
145
+ events.append(self._make_event(
146
+ event_id=f"meeting-{source_id}",
147
+ event_kind="meeting",
148
+ subject=f"transcript:{source_id}",
149
+ object=self._summary_line(transcript, points),
150
+ source=source,
151
+ participants=parts,
152
+ started_at=ts,
153
+ ))
154
+
155
+ # Event 2-n: Decisions (from cue words in point content)
156
+ decision_idx = 1
157
+ for p in points:
158
+ content = p.get("content", "")
159
+ if self._has_cue(content, _DECISION_WORDS):
160
+ events.append(self._make_event(
161
+ event_id=f"decision-{source_id}-{decision_idx}",
162
+ event_kind="decision",
163
+ subject=parts[0] if parts else "unknown",
164
+ object=content[:200],
165
+ source=source,
166
+ participants=parts,
167
+ started_at=ts,
168
+ parent_event=f"meeting-{source_id}",
169
+ ))
170
+ decision_idx += 1
171
+
172
+ # Event n+: Friction (from NAND operators + conflict language)
173
+ friction_idx = 1
174
+ for op in operators:
175
+ otype = op.get("operator", {}).get("op_type", "")
176
+ if otype == "NAND":
177
+ events.append(self._make_event(
178
+ event_id=f"friction-{source_id}-{friction_idx}",
179
+ event_kind="friction",
180
+ subject="extraction",
181
+ object=op.get("content", "")[:200],
182
+ source=source,
183
+ participants=parts,
184
+ started_at=ts,
185
+ parent_event=f"meeting-{source_id}",
186
+ ))
187
+ friction_idx += 1
188
+
189
+ # Check point content for friction/conflict language (in addition to NAND operators)
190
+ for p in points:
191
+ content = p.get("content", "")
192
+ if self._has_cue(content, _FRICTION_WORDS):
193
+ # Don't duplicate if already covered by a NAND operator
194
+ # (skip — NAND is stronger signal, already captured above)
195
+ pass
196
+
197
+ # Fallback: if <3 events, add milestone events for significant content
198
+ milestone_idx = 1
199
+ while len(events) < 3:
200
+ # Pick the next significant point as a milestone
201
+ for p in points:
202
+ content = p.get("content", "")
203
+ if len(content) > 60 and self._has_cue(content, _MILESTONE_WORDS):
204
+ # Check if already captured as another event type
205
+ already = any(
206
+ e["eventKind"] in ("decision", "friction")
207
+ and content[:100] in e.get("object", "")
208
+ for e in events
209
+ )
210
+ if not already:
211
+ events.append(self._make_event(
212
+ event_id=f"milestone-{source_id}-{milestone_idx}",
213
+ event_kind="milestone",
214
+ subject=parts[0] if parts else "unknown",
215
+ object=content[:200],
216
+ source=source,
217
+ participants=parts,
218
+ started_at=ts,
219
+ parent_event=f"meeting-{source_id}",
220
+ ))
221
+ milestone_idx += 1
222
+ if len(events) >= 3:
223
+ break
224
+ break # ponytail: single pass only
225
+
226
+ # Absolute fallback: add generic session event
227
+ fallback_idx = 1
228
+ while len(events) < 3:
229
+ # Capture longest point as generic observation
230
+ if points:
231
+ longest = max(points, key=lambda p: len(p.get("content", "")))
232
+ content = longest.get("content", "")
233
+ if content and not any(content[:100] in e.get("object", "") for e in events):
234
+ events.append(self._make_event(
235
+ event_id=f"observation-{source_id}-{fallback_idx}",
236
+ event_kind="observation",
237
+ subject=parts[0] if parts else "unknown",
238
+ object=content[:200],
239
+ source=source,
240
+ participants=parts,
241
+ started_at=ts,
242
+ parent_event=f"meeting-{source_id}",
243
+ ))
244
+ fallback_idx += 1
245
+ else:
246
+ break # can't produce more unique events
247
+ else:
248
+ break # no points at all
249
+
250
+ return events
251
+
252
+ @staticmethod
253
+ def _emit_event(api: EventAPI, event: dict) -> None:
254
+ """Emit an EventRecorded event to the log + projection."""
255
+ record = {
256
+ "version": "1.0",
257
+ "type": "EventRecorded",
258
+ "event": event,
259
+ "createdAt": _now(),
260
+ }
261
+ api.log.append(record)
262
+ if api.projection is not None:
263
+ api.projection.apply(record)
264
+
265
+ @staticmethod
266
+ def _make_event(
267
+ *,
268
+ event_id: str,
269
+ event_kind: str,
270
+ subject: str,
271
+ object: str,
272
+ source: str,
273
+ participants: list[str] | None = None,
274
+ started_at: str | None = None,
275
+ parent_event: str | None = None,
276
+ ) -> dict:
277
+ return {
278
+ "eventId": event_id,
279
+ "eventKind": event_kind,
280
+ "subject": subject,
281
+ "object": object,
282
+ "startedAt": started_at or _now(),
283
+ "endedAt": None,
284
+ "parentEvent": parent_event,
285
+ "childEvents": [],
286
+ "participants": participants or [],
287
+ "classificationLevel": "internal",
288
+ "format": "jsonl",
289
+ "source": source,
290
+ }
291
+
292
+ @staticmethod
293
+ def _has_cue(text: str, words: tuple[str, ...]) -> bool:
294
+ low = text.lower()
295
+ return any(w in low for w in words)
296
+
297
+ @staticmethod
298
+ def _summary_line(transcript: str, points: list[dict]) -> str:
299
+ """First meaningful line for a brief meeting object."""
300
+ for p in points:
301
+ content = p.get("content", "")
302
+ if len(content) >= 30:
303
+ return content[:200]
304
+ # fallback: first non-empty line from transcript
305
+ for line in transcript.splitlines():
306
+ stripped = line.strip()
307
+ if len(stripped) > 20 and ":" in stripped:
308
+ return stripped[stripped.index(":") + 1:].strip()[:200]
309
+ return transcript.splitlines()[0][:200] if transcript else "(empty)"
310
+
311
+ @staticmethod
312
+ def _extract_participants(transcript: str) -> list[str]:
313
+ """Extract unique speaker names from transcript."""
314
+ speaker_re = re.compile(r"^\s*([A-Z][\w .'-]{0,40}):", re.MULTILINE)
315
+ seen = set()
316
+ for m in speaker_re.finditer(transcript):
317
+ name = m.group(1).strip()
318
+ if name and name not in seen:
319
+ seen.add(name)
320
+ return sorted(seen)
321
+
322
+
323
+ # ── Module-level convenience ────────────────────────────────────────
324
+
325
+ def mine_conversation(
326
+ transcript: str,
327
+ source_id: str,
328
+ api: EventAPI,
329
+ *,
330
+ model: Any | None = None,
331
+ participants: list[str] | None = None,
332
+ ) -> dict:
333
+ """Convenience: mine a conversation transcript → Events + Points.
334
+
335
+ Returns: {events: N, points: M, operators: K, event_ids: [...]}
336
+ """
337
+ miner = ConversationMiner(model)
338
+ return miner.mine(transcript, source_id, api, participants=participants)
tortoise/models.py ADDED
@@ -0,0 +1,109 @@
1
+ """Model backends for the extractor stages.
2
+
3
+ A Model is a text-in / text-out completer. Stages own the prompts and parsing, so
4
+ swapping a model is a config change, not a code change — which is what lets us
5
+ benchmark "what we can get away with" per stage (cheap model for point extraction,
6
+ large reasoning model for relations).
7
+
8
+ `OpenAICompatModel` covers DeepSeek, Gemini (OpenAI-compat endpoint), and local
9
+ Ollama with one adapter. Its transport (`complete`) is thin and untested without a
10
+ network/key; the tested surface is `build_request` / `parse_response`.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import os
16
+ import urllib.request
17
+ from typing import Protocol, runtime_checkable
18
+
19
+
20
+ @runtime_checkable
21
+ class Model(Protocol):
22
+ id: str
23
+ def complete(self, *, system: str, user: str) -> str: ...
24
+
25
+
26
+ class OpenAICompatModel:
27
+ def __init__(self, *, id: str, base_url: str, api_key_env: str | None = "OPENAI_API_KEY",
28
+ temperature: float = 0.0, timeout: int = 60):
29
+ # api_key_env=None → no Authorization header.
30
+ self.id = id
31
+ self.base_url = base_url.rstrip("/")
32
+ self.api_key_env = api_key_env
33
+ self.temperature = temperature
34
+ self.timeout = timeout
35
+
36
+ def build_request(self, system: str, user: str) -> dict:
37
+ return {
38
+ "model": self.id,
39
+ "temperature": self.temperature,
40
+ "response_format": {"type": "json_object"},
41
+ "messages": [
42
+ {"role": "system", "content": system},
43
+ {"role": "user", "content": user},
44
+ ],
45
+ }
46
+
47
+ @staticmethod
48
+ def parse_response(data: dict) -> str:
49
+ return data["choices"][0]["message"]["content"]
50
+
51
+ def _headers(self) -> dict:
52
+ h = {"Content-Type": "application/json"}
53
+ if self.api_key_env:
54
+ key = os.environ.get(self.api_key_env)
55
+ if not key:
56
+ raise RuntimeError(
57
+ f"{self.id}: env var {self.api_key_env} is not set")
58
+ h["Authorization"] = f"Bearer {key}"
59
+ return h
60
+
61
+ def complete(self, *, system: str, user: str) -> str:
62
+ body = json.dumps(self.build_request(system, user)).encode("utf-8")
63
+ req = urllib.request.Request(
64
+ f"{self.base_url}/chat/completions", data=body, headers=self._headers())
65
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
66
+ return self.parse_response(json.loads(r.read()))
67
+
68
+
69
+ class OllamaModel:
70
+ """Native Ollama /api/chat with a `think` toggle. The OpenAI-compat endpoint
71
+ can't control qwen3's thinking, so we hit the native endpoint directly.
72
+ think=False for the mechanical point tier (thinking is wasted and ~50x slower);
73
+ think=True for the relation tier, which needs reasoning to find operators."""
74
+
75
+ def __init__(self, *, id: str, base_url: str = "http://localhost:11434",
76
+ timeout: int = 300, think: bool = False, temperature: float = 0.0):
77
+ self.id = id
78
+ self.base_url = base_url.rstrip("/")
79
+ self.timeout = timeout
80
+ self.think = think
81
+ self.temperature = temperature
82
+
83
+ def build_request(self, system: str, user: str) -> dict:
84
+ req = {
85
+ "model": self.id,
86
+ "think": self.think,
87
+ "stream": False,
88
+ "format": "json",
89
+ "messages": [
90
+ {"role": "system", "content": system},
91
+ {"role": "user", "content": user},
92
+ ],
93
+ }
94
+ if "options" not in req:
95
+ req["options"] = {}
96
+ req["options"]["temperature"] = self.temperature
97
+ return req
98
+
99
+ @staticmethod
100
+ def parse_response(data: dict) -> str:
101
+ return data["message"]["content"]
102
+
103
+ def complete(self, *, system: str, user: str) -> str:
104
+ body = json.dumps(self.build_request(system, user)).encode("utf-8")
105
+ req = urllib.request.Request(
106
+ f"{self.base_url}/api/chat", data=body,
107
+ headers={"Content-Type": "application/json"})
108
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
109
+ return self.parse_response(json.loads(r.read()))
tortoise/monitoring.py ADDED
@@ -0,0 +1,133 @@
1
+ """GAP-09b #6996: Health checks + Prometheus metrics + cost tracking.
2
+
3
+ #7395: Auth-gated — requires Bearer token when TORTOISE_API_KEY is set.
4
+ Binds 127.0.0.1 by default (not 0.0.0.0).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ import json
10
+ from http.server import HTTPServer, BaseHTTPRequestHandler
11
+
12
+ from prometheus_client import Counter, Histogram, generate_latest
13
+
14
+ # Auth functions imported lazily (in _Handler.do_GET) to avoid
15
+ # triggering TORTOISE_SECRET_PEPPER requirement at module import time (#67).
16
+
17
+ _start = time.monotonic()
18
+ _last_ingest: float | None = None
19
+ _sdk = None # set by register()
20
+
21
+ # Prometheus metrics
22
+ REQUEST_COUNT = Counter("tortoise_requests_total", "Total HTTP requests", ["endpoint"])
23
+ REQUEST_LATENCY = Histogram("tortoise_request_latency_seconds", "Request latency")
24
+ ERROR_COUNT = Counter("tortoise_errors_total", "Total errors")
25
+ TEAM_COST = Counter("tortoise_team_cost_cents", "Cost by team", ["team"])
26
+
27
+
28
+ def register(sdk) -> None:
29
+ """Wire SDK so /health can check FalkorDB connectivity + graph size."""
30
+ global _sdk
31
+ _sdk = sdk
32
+
33
+
34
+ def record_ingest() -> None:
35
+ global _last_ingest
36
+ _last_ingest = time.time()
37
+
38
+
39
+ def record_error() -> None:
40
+ ERROR_COUNT.inc()
41
+
42
+
43
+ def record_cost(team: str, cents: int) -> None:
44
+ """Track LLM/tool cost for a team. cents is integer (avoids float drift)."""
45
+ TEAM_COST.labels(team=team).inc(cents)
46
+
47
+
48
+ def _check_falkordb() -> tuple[bool, str]:
49
+ """Test FalkorDB connectivity. Returns (ok, message)."""
50
+ if _sdk is None:
51
+ return False, "no_sdk_registered"
52
+ try:
53
+ proj = _sdk._get_proj()
54
+ proj.g.query("MATCH (n) RETURN count(n) LIMIT 1")
55
+ return True, "connected"
56
+ except Exception as e:
57
+ return False, str(e)[:200]
58
+
59
+
60
+ def _counter_val(counter) -> int:
61
+ """Extract current value of a Counter via public collect() API."""
62
+ for m in counter.collect():
63
+ for s in m.samples:
64
+ if s.name.endswith("_total") and not s.name.endswith("_created_total"):
65
+ return int(s.value)
66
+ return 0
67
+
68
+
69
+ def metrics() -> dict:
70
+ """Return {status, falkordb, graph_size, last_ingest, errors, uptime}."""
71
+ falkor_ok, falkor_msg = _check_falkordb()
72
+ graph_size = 0
73
+ try:
74
+ if _sdk:
75
+ graph_size = sum(_sdk.taxonomy().values())
76
+ except Exception:
77
+ record_error()
78
+ return {
79
+ "status": "ok" if falkor_ok else "degraded",
80
+ "falkordb": falkor_msg,
81
+ "graph_size": graph_size,
82
+ "last_ingest": _last_ingest,
83
+ "errors": _counter_val(ERROR_COUNT),
84
+ "uptime": round(time.monotonic() - _start, 2),
85
+ }
86
+
87
+
88
+ class _Handler(BaseHTTPRequestHandler):
89
+ def do_GET(self):
90
+ # Auth gate (#7395): require valid Bearer token in prod mode
91
+ from tortoise.auth import require_auth, is_dev_mode # lazy — #67
92
+ if not is_dev_mode():
93
+ headers = {k.lower(): v for k, v in self.headers.items()}
94
+ if not require_auth(headers):
95
+ self.send_response(401)
96
+ self.send_header("Content-Type", "application/json")
97
+ self.end_headers()
98
+ self.wfile.write(json.dumps({"error": "unauthorized"}).encode())
99
+ return
100
+
101
+ if self.path == "/health":
102
+ self._handle_endpoint("health", lambda: json.dumps(metrics()).encode(),
103
+ "application/json")
104
+ elif self.path == "/metrics":
105
+ self._handle_endpoint("metrics", generate_latest,
106
+ "text/plain; version=0.0.4")
107
+ else:
108
+ self.send_response(404)
109
+ self.end_headers()
110
+
111
+ def _handle_endpoint(self, endpoint: str, body_fn, content_type: str):
112
+ REQUEST_COUNT.labels(endpoint=endpoint).inc()
113
+ with REQUEST_LATENCY.time():
114
+ try:
115
+ body = body_fn()
116
+ except Exception:
117
+ record_error()
118
+ self.send_response(500)
119
+ self.end_headers()
120
+ return
121
+ self.send_response(200)
122
+ self.send_header("Content-Type", content_type)
123
+ self.send_header("Content-Length", str(len(body)))
124
+ self.end_headers()
125
+ self.wfile.write(body)
126
+
127
+ def log_message(self, *args):
128
+ pass # silence logs
129
+
130
+
131
+ def serve_health(port: int = 9090, bind: str = "127.0.0.1") -> None:
132
+ """Standalone /health + /metrics HTTP server. Auth-gated in prod mode (#7395)."""
133
+ HTTPServer((bind, port), _Handler).serve_forever()