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,199 @@
|
|
|
1
|
+
"""GAP-21 #7009: Linear connector — GraphQL → issue/cycle → EventRecorded JSONL.
|
|
2
|
+
|
|
3
|
+
Polls Linear's GraphQL API for issues and cycles, maps to EventRecorded events.
|
|
4
|
+
Requires: LINEAR_API_KEY env var. Zero Python deps outside stdlib.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import urllib.request
|
|
11
|
+
import urllib.error
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _now_iso() -> str:
|
|
17
|
+
return datetime.now(timezone.utc).isoformat()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
_LINEAR_API = "https://api.linear.app/graphql"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class LinearConnector:
|
|
24
|
+
"""Poll Linear issues/cycles via GraphQL API. No webhook support (yet)."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, config: dict[str, Any] | None = None, api=None):
|
|
27
|
+
cfg = config or {}
|
|
28
|
+
# Env-first (matches Slack/GitHub pattern #324): distinguish "unset"
|
|
29
|
+
# from "set to empty" so the loader's stripped config ("api_key": "")
|
|
30
|
+
# never shadows a real LINEAR_API_KEY env var.
|
|
31
|
+
env_api_key = os.environ.get("LINEAR_API_KEY")
|
|
32
|
+
self.api_key = env_api_key if env_api_key is not None else cfg.get("api_key", "")
|
|
33
|
+
self.team_id = cfg.get("team_id", "")
|
|
34
|
+
self.limit = int(cfg.get("limit", 100))
|
|
35
|
+
self.days = int(cfg.get("days", 30)) # lookback window
|
|
36
|
+
self.api = api
|
|
37
|
+
|
|
38
|
+
def _query(self, query: str, variables: dict | None = None) -> dict:
|
|
39
|
+
"""Execute a Linear GraphQL query. Returns parsed JSON response."""
|
|
40
|
+
if not self.api_key:
|
|
41
|
+
return {}
|
|
42
|
+
|
|
43
|
+
payload = json.dumps({"query": query, "variables": variables or {}}).encode()
|
|
44
|
+
req = urllib.request.Request(
|
|
45
|
+
_LINEAR_API,
|
|
46
|
+
data=payload,
|
|
47
|
+
headers={
|
|
48
|
+
"Authorization": self.api_key,
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
},
|
|
51
|
+
method="POST",
|
|
52
|
+
)
|
|
53
|
+
try:
|
|
54
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
55
|
+
data = json.loads(resp.read())
|
|
56
|
+
if "errors" in data:
|
|
57
|
+
return {} # ponytail: GraphQL-level errors, surface if needed
|
|
58
|
+
return data
|
|
59
|
+
except (urllib.error.URLError, json.JSONDecodeError, OSError):
|
|
60
|
+
return {}
|
|
61
|
+
|
|
62
|
+
# ── Polling ────────────────────────────────────────────────────
|
|
63
|
+
|
|
64
|
+
def poll(self) -> list[dict]:
|
|
65
|
+
"""Fetch issues + cycles → EventRecorded dicts."""
|
|
66
|
+
if not self.api_key:
|
|
67
|
+
return []
|
|
68
|
+
events: list[dict] = []
|
|
69
|
+
events.extend(self._poll_issues())
|
|
70
|
+
events.extend(self._poll_cycles())
|
|
71
|
+
return events
|
|
72
|
+
|
|
73
|
+
def _poll_issues(self) -> list[dict]:
|
|
74
|
+
query = """
|
|
75
|
+
query Issues($first: Int!, $filter: IssueFilter) {
|
|
76
|
+
issues(first: $first, filter: $filter) {
|
|
77
|
+
nodes {
|
|
78
|
+
id
|
|
79
|
+
identifier
|
|
80
|
+
title
|
|
81
|
+
description
|
|
82
|
+
state { name type }
|
|
83
|
+
createdAt
|
|
84
|
+
updatedAt
|
|
85
|
+
completedAt
|
|
86
|
+
canceledAt
|
|
87
|
+
assignee { name email }
|
|
88
|
+
team { name key }
|
|
89
|
+
cycle { name }
|
|
90
|
+
priority
|
|
91
|
+
url
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
"""
|
|
96
|
+
variables = {"first": self.limit}
|
|
97
|
+
filter_dict: dict[str, Any] = {}
|
|
98
|
+
if self.team_id:
|
|
99
|
+
filter_dict["team"] = {"id": {"eq": self.team_id}}
|
|
100
|
+
if filter_dict:
|
|
101
|
+
variables["filter"] = filter_dict
|
|
102
|
+
|
|
103
|
+
result = self._query(query, variables)
|
|
104
|
+
issues = result.get("data", {}).get("issues", {}).get("nodes", [])
|
|
105
|
+
return [ev for issue in (issues or [])
|
|
106
|
+
if (ev := self._issue_to_event(issue))]
|
|
107
|
+
|
|
108
|
+
def _poll_cycles(self) -> list[dict]:
|
|
109
|
+
query = """
|
|
110
|
+
query Cycles($first: Int!) {
|
|
111
|
+
cycles(first: $first) {
|
|
112
|
+
nodes {
|
|
113
|
+
id
|
|
114
|
+
number
|
|
115
|
+
name
|
|
116
|
+
startsAt
|
|
117
|
+
endsAt
|
|
118
|
+
completedAt
|
|
119
|
+
team { name key }
|
|
120
|
+
progress
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
"""
|
|
125
|
+
variables: dict[str, Any] = {"first": min(self.limit, 50)}
|
|
126
|
+
if self.team_id:
|
|
127
|
+
variables["teamId"] = self.team_id
|
|
128
|
+
result = self._query(query, variables)
|
|
129
|
+
cycles = result.get("data", {}).get("cycles", {}).get("nodes", [])
|
|
130
|
+
return [ev for cycle in (cycles or [])
|
|
131
|
+
if (ev := self._cycle_to_event(cycle))]
|
|
132
|
+
|
|
133
|
+
def ingest(self, proj) -> int:
|
|
134
|
+
"""Poll + apply to projection. Returns count of applied events."""
|
|
135
|
+
events = self.poll()
|
|
136
|
+
count = 0
|
|
137
|
+
for ev in events:
|
|
138
|
+
proj.apply(ev)
|
|
139
|
+
count += 1
|
|
140
|
+
return count
|
|
141
|
+
|
|
142
|
+
# ── Event mapping ──────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
def _issue_to_event(self, issue: dict) -> dict | None:
|
|
145
|
+
ident = issue.get("identifier", "")
|
|
146
|
+
title = issue.get("title", "")
|
|
147
|
+
if not ident or not title:
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
state_info = issue.get("state", {}) or {}
|
|
151
|
+
state = state_info.get("name", "unknown").lower()
|
|
152
|
+
team = issue.get("team", {}) or {}
|
|
153
|
+
team_key = team.get("key", "")
|
|
154
|
+
assignee = issue.get("assignee", {}) or {}
|
|
155
|
+
|
|
156
|
+
created = issue.get("createdAt", "")
|
|
157
|
+
ended = issue.get("completedAt") or issue.get("canceledAt")
|
|
158
|
+
|
|
159
|
+
participants = [assignee.get("email", "")] if assignee.get("email") else []
|
|
160
|
+
|
|
161
|
+
normalized_state = state.replace(" ", "_").lower()
|
|
162
|
+
return {
|
|
163
|
+
"type": "EventRecorded",
|
|
164
|
+
"eventId": f"linear-issue-{ident}",
|
|
165
|
+
"eventKind": f"linear.issue.{'completed' if ended else normalized_state}",
|
|
166
|
+
"subject": f"issue:linear:{ident}",
|
|
167
|
+
"object": title[:200],
|
|
168
|
+
"startedAt": created,
|
|
169
|
+
"endedAt": ended,
|
|
170
|
+
"source": f"linear:{team_key}",
|
|
171
|
+
"sourceKind": "linear_card",
|
|
172
|
+
"participants": participants,
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
def _cycle_to_event(self, cycle: dict) -> dict | None:
|
|
176
|
+
number = cycle.get("number")
|
|
177
|
+
name = cycle.get("name", "")
|
|
178
|
+
if number is None or not name:
|
|
179
|
+
return None
|
|
180
|
+
|
|
181
|
+
team = cycle.get("team", {}) or {}
|
|
182
|
+
team_key = team.get("key", "")
|
|
183
|
+
|
|
184
|
+
starts = cycle.get("startsAt", "")
|
|
185
|
+
ends = cycle.get("endsAt", "")
|
|
186
|
+
completed = cycle.get("completedAt")
|
|
187
|
+
|
|
188
|
+
return {
|
|
189
|
+
"type": "EventRecorded",
|
|
190
|
+
"eventId": f"linear-cycle-{team_key}-{number}",
|
|
191
|
+
"eventKind": "linear.cycle.completed" if completed else "linear.cycle.active",
|
|
192
|
+
"subject": f"cycle:linear:{team_key}#{number}",
|
|
193
|
+
"object": name[:200],
|
|
194
|
+
"startedAt": starts,
|
|
195
|
+
"endedAt": completed or None,
|
|
196
|
+
"source": f"linear:{team_key}",
|
|
197
|
+
"sourceKind": "linear_card",
|
|
198
|
+
"participants": [],
|
|
199
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""P1-5 #6977 / GAP-20 #7008: Slack connector.
|
|
2
|
+
|
|
3
|
+
Polls Slack channels for messages and threads, maps them to EventRecorded JSONL.
|
|
4
|
+
Requires: slack-sdk (pip install slack-sdk).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import hmac
|
|
10
|
+
import hashlib
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
17
|
+
from typing import Any, Callable
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _now_iso() -> str:
|
|
23
|
+
return datetime.now(timezone.utc).isoformat()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SlackConnector:
|
|
27
|
+
"""Poll Slack channels/threads via Slack SDK + optional Events API webhook."""
|
|
28
|
+
|
|
29
|
+
def __init__(self, config: dict[str, Any] | None = None, api=None):
|
|
30
|
+
cfg = config or {}
|
|
31
|
+
# Env vars take precedence over config for secrets (#324)
|
|
32
|
+
# os.environ.get returns None when not set; explicit None check
|
|
33
|
+
# so we can distinguish "not set" from "set to empty string"
|
|
34
|
+
env_token = os.environ.get("SLACK_BOT_TOKEN")
|
|
35
|
+
self.token = env_token if env_token is not None else cfg.get("token", "")
|
|
36
|
+
env_signing = os.environ.get("SLACK_SIGNING_SECRET")
|
|
37
|
+
self.signing_secret = (
|
|
38
|
+
env_signing if env_signing is not None else cfg.get("signing_secret", "")
|
|
39
|
+
)
|
|
40
|
+
self.channel_id = cfg.get("channel_id", "")
|
|
41
|
+
self.limit = int(cfg.get("limit", 100))
|
|
42
|
+
self.days = int(cfg.get("days", 7))
|
|
43
|
+
self.webhook_port = int(cfg.get("webhook_port", 0))
|
|
44
|
+
self.api = api
|
|
45
|
+
self._server: HTTPServer | None = None
|
|
46
|
+
self._thread: threading.Thread | None = None
|
|
47
|
+
if not self.token:
|
|
48
|
+
logger.warning(
|
|
49
|
+
"SLACK_BOT_TOKEN not set — Slack connector will be a no-op. "
|
|
50
|
+
"Set SLACK_BOT_TOKEN env var or 'token' in connector config."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def _client(self):
|
|
54
|
+
"""Lazy-init Slack WebClient (imports only if used)."""
|
|
55
|
+
from slack_sdk import WebClient
|
|
56
|
+
return WebClient(token=self.token)
|
|
57
|
+
|
|
58
|
+
# ── Polling ────────────────────────────────────────────────────
|
|
59
|
+
|
|
60
|
+
def poll(self) -> list[dict]:
|
|
61
|
+
"""Fetch messages from configured channel → EventRecorded dicts."""
|
|
62
|
+
if not self.token or not self.channel_id:
|
|
63
|
+
return []
|
|
64
|
+
|
|
65
|
+
client = self._client()
|
|
66
|
+
events: list[dict] = []
|
|
67
|
+
|
|
68
|
+
# Calculate oldest timestamp for the time window
|
|
69
|
+
oldest = str(time.time() - self.days * 86400)
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
result = client.conversations_history(
|
|
73
|
+
channel=self.channel_id,
|
|
74
|
+
limit=self.limit,
|
|
75
|
+
oldest=oldest,
|
|
76
|
+
)
|
|
77
|
+
for msg in result.get("messages", []):
|
|
78
|
+
ev = self._message_to_event(msg)
|
|
79
|
+
if ev:
|
|
80
|
+
events.append(ev)
|
|
81
|
+
|
|
82
|
+
# Fetch thread replies if any
|
|
83
|
+
if msg.get("thread_ts") and msg.get("reply_count", 0) > 0:
|
|
84
|
+
thread = client.conversations_replies(
|
|
85
|
+
channel=self.channel_id,
|
|
86
|
+
ts=msg["thread_ts"],
|
|
87
|
+
limit=min(self.limit, 50),
|
|
88
|
+
)
|
|
89
|
+
for reply in thread.get("messages", []):
|
|
90
|
+
if reply.get("ts") != msg.get("thread_ts"):
|
|
91
|
+
rev = self._message_to_event(reply, parent_ts=msg["thread_ts"])
|
|
92
|
+
if rev:
|
|
93
|
+
events.append(rev)
|
|
94
|
+
except (ConnectionError, TimeoutError, OSError):
|
|
95
|
+
pass # ponytail: network issues → return empty, don't crash
|
|
96
|
+
|
|
97
|
+
return events
|
|
98
|
+
|
|
99
|
+
def ingest(self, proj) -> int:
|
|
100
|
+
"""Poll + apply to projection. Returns count of applied events."""
|
|
101
|
+
events = self.poll()
|
|
102
|
+
count = 0
|
|
103
|
+
for ev in events:
|
|
104
|
+
proj.apply(ev)
|
|
105
|
+
count += 1
|
|
106
|
+
return count
|
|
107
|
+
|
|
108
|
+
# ── Webhook (Events API) ───────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
def start_webhook(self, on_event: Callable[[dict], None] | None = None) -> int:
|
|
111
|
+
if not self.webhook_port:
|
|
112
|
+
return 0
|
|
113
|
+
|
|
114
|
+
secret = self.signing_secret.encode() if self.signing_secret else None
|
|
115
|
+
connector = self
|
|
116
|
+
|
|
117
|
+
class Handler(BaseHTTPRequestHandler):
|
|
118
|
+
def do_POST(self):
|
|
119
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
120
|
+
body = self.rfile.read(length)
|
|
121
|
+
|
|
122
|
+
# Verify Slack signature
|
|
123
|
+
if secret:
|
|
124
|
+
ts = self.headers.get("X-Slack-Request-Timestamp", "")
|
|
125
|
+
sig = self.headers.get("X-Slack-Signature", "")
|
|
126
|
+
if not _verify_slack_sig(secret, ts, sig, body):
|
|
127
|
+
self.send_response(403)
|
|
128
|
+
self.end_headers()
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
try:
|
|
132
|
+
payload = json.loads(body)
|
|
133
|
+
except json.JSONDecodeError:
|
|
134
|
+
self.send_response(400)
|
|
135
|
+
self.end_headers()
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
# Slack URL verification challenge
|
|
139
|
+
if payload.get("type") == "url_verification":
|
|
140
|
+
challenge = payload.get("challenge", "")
|
|
141
|
+
self.send_response(200)
|
|
142
|
+
self.send_header("Content-Type", "text/plain")
|
|
143
|
+
self.end_headers()
|
|
144
|
+
self.wfile.write(challenge.encode())
|
|
145
|
+
return
|
|
146
|
+
|
|
147
|
+
# Handle event callbacks
|
|
148
|
+
event_data = payload.get("event", {})
|
|
149
|
+
if event_data.get("type") == "message" and "subtype" not in event_data:
|
|
150
|
+
ev = connector._message_to_event(event_data)
|
|
151
|
+
if ev:
|
|
152
|
+
if on_event:
|
|
153
|
+
on_event(ev)
|
|
154
|
+
if connector.api:
|
|
155
|
+
connector.api.get_proj().apply(ev)
|
|
156
|
+
|
|
157
|
+
self.send_response(200)
|
|
158
|
+
self.end_headers()
|
|
159
|
+
|
|
160
|
+
def log_message(self, format, *args):
|
|
161
|
+
pass
|
|
162
|
+
|
|
163
|
+
self._server = HTTPServer(("127.0.0.1", self.webhook_port), Handler)
|
|
164
|
+
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
165
|
+
self._thread.start()
|
|
166
|
+
return self.webhook_port
|
|
167
|
+
|
|
168
|
+
def stop_webhook(self) -> None:
|
|
169
|
+
if self._server:
|
|
170
|
+
self._server.shutdown()
|
|
171
|
+
self._server = None
|
|
172
|
+
self._thread = None
|
|
173
|
+
|
|
174
|
+
# ── Event mapping ──────────────────────────────────────────────
|
|
175
|
+
|
|
176
|
+
def _message_to_event(self, msg: dict, parent_ts: str | None = None) -> dict | None:
|
|
177
|
+
"""Map Slack message → EventRecorded dict."""
|
|
178
|
+
text = msg.get("text", "")
|
|
179
|
+
ts = msg.get("ts", "")
|
|
180
|
+
if not text or not ts:
|
|
181
|
+
return None
|
|
182
|
+
|
|
183
|
+
user = msg.get("user", "unknown")
|
|
184
|
+
thread_ts = parent_ts or msg.get("thread_ts")
|
|
185
|
+
channel = self.channel_id or msg.get("channel", "")
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
"type": "EventRecorded",
|
|
189
|
+
"eventId": f"slack-msg-{channel}-{ts.replace('.', '-')}",
|
|
190
|
+
"eventKind": "slack.message.thread_reply" if parent_ts else "slack.message",
|
|
191
|
+
"subject": f"slack:{channel}:{user}",
|
|
192
|
+
"object": text[:200],
|
|
193
|
+
"startedAt": _ts_to_iso(ts),
|
|
194
|
+
"endedAt": None,
|
|
195
|
+
"source": f"slack:{channel}",
|
|
196
|
+
"sourceKind": "slack_message",
|
|
197
|
+
"participants": [user],
|
|
198
|
+
"parentEvent": f"slack-msg-{channel}-{thread_ts.replace('.', '-')}" if parent_ts else None,
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _ts_to_iso(ts: str) -> str:
|
|
203
|
+
"""Convert Slack timestamp (e.g. '1690000000.123456') to ISO format."""
|
|
204
|
+
try:
|
|
205
|
+
return datetime.fromtimestamp(float(ts), tz=timezone.utc).isoformat()
|
|
206
|
+
except (ValueError, TypeError):
|
|
207
|
+
return _now_iso()
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _verify_slack_sig(secret: bytes, timestamp: str, sig: str, body: bytes) -> bool:
|
|
211
|
+
"""Verify Slack request signature (HMAC-SHA256)."""
|
|
212
|
+
if not timestamp or not sig:
|
|
213
|
+
return False
|
|
214
|
+
# Reject old requests (> 5 min)
|
|
215
|
+
try:
|
|
216
|
+
if abs(time.time() - float(timestamp)) > 300:
|
|
217
|
+
return False
|
|
218
|
+
except (ValueError, TypeError):
|
|
219
|
+
return False
|
|
220
|
+
base = f"v0:{timestamp}:{body.decode('utf-8', errors='replace')}"
|
|
221
|
+
expected = hmac.new(secret, base.encode(), hashlib.sha256).hexdigest()
|
|
222
|
+
return hmac.compare_digest(f"v0={expected}", sig)
|
tortoise/consistency.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Startup consistency check — verify event log Point count matches graph.
|
|
2
|
+
|
|
3
|
+
The event log is the source of truth; the projection is a derived view.
|
|
4
|
+
This module verifies the counts haven't diverged (quick check, not full diff).
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from .projection import fold
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def check_consistency(log_path: str, projection) -> dict:
|
|
12
|
+
"""Fold the event log and compare Point count against the graph.
|
|
13
|
+
|
|
14
|
+
projection must have .query(cypher) returning an object with .result_set.
|
|
15
|
+
Returns {ok, log_points, db_points, delta}.
|
|
16
|
+
"""
|
|
17
|
+
from .log import EventLog
|
|
18
|
+
|
|
19
|
+
log = EventLog(log_path)
|
|
20
|
+
points = fold(log.read_all())
|
|
21
|
+
log_count = len(points)
|
|
22
|
+
|
|
23
|
+
db_rows = projection.query(
|
|
24
|
+
"MATCH (n:Point) RETURN count(n)"
|
|
25
|
+
).result_set
|
|
26
|
+
db_count = db_rows[0][0] if db_rows else 0
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
"ok": log_count == db_count,
|
|
30
|
+
"log_points": log_count,
|
|
31
|
+
"db_points": db_count,
|
|
32
|
+
"delta": log_count - db_count,
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def recover_from_log(events_dir: str, projection) -> dict:
|
|
37
|
+
"""Rebuild a projection from a JSONL event-log dir when its graph was lost.
|
|
38
|
+
|
|
39
|
+
Corruption recovery (#428): the event log is the source of truth, the
|
|
40
|
+
projection a derived view. An embedded DB that answers 0 nodes while its
|
|
41
|
+
adjacent JSONL log has events was lost — redislite starts fresh when its
|
|
42
|
+
RDB is corrupt, an interrupted restore left an empty graph, or the DB was
|
|
43
|
+
deleted out from under the log. Rebuild = wipe + full replay.
|
|
44
|
+
|
|
45
|
+
Safety (mirrors migrate_db's 3-way discriminator):
|
|
46
|
+
- Only rebuilds when db has 0 total nodes and the log has > 0 events
|
|
47
|
+
(the "lost DB" case). Partial divergence (0 < db < log) is left
|
|
48
|
+
alone — the graph may hold SDK-created points that never appear in
|
|
49
|
+
the log; a rebuild would destroy them. db >= log is healthy (the log
|
|
50
|
+
is append-only).
|
|
51
|
+
- Only rebuilds from an UNambiguous log: exactly one adjacent .jsonl.
|
|
52
|
+
Multiple logs could be mid-restore artifacts (backup copy + live
|
|
53
|
+
log); auto-rebuilding the wrong one loses data, so we refuse.
|
|
54
|
+
- Replays faithfully via projection.apply() (same path as restore) —
|
|
55
|
+
NOT rebuild_all, which drops context for v2+ events (#49). A
|
|
56
|
+
lossy rebuild is worse than no recovery for a transparent path.
|
|
57
|
+
- Query/log failures are caught and reported in the result, never
|
|
58
|
+
raised — the caller decides fail-loud policy. Torn trailing lines
|
|
59
|
+
(crash mid-append) are skipped, not fatal.
|
|
60
|
+
|
|
61
|
+
Returns {recovered, log_points, db_points, reason}.
|
|
62
|
+
"""
|
|
63
|
+
import json as _json
|
|
64
|
+
import os
|
|
65
|
+
|
|
66
|
+
def _node_count() -> int | None:
|
|
67
|
+
try:
|
|
68
|
+
rows = projection.query("MATCH (n) RETURN count(n)").result_set
|
|
69
|
+
return int(rows[0][0]) if rows and rows[0][0] is not None else 0
|
|
70
|
+
except Exception:
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
db_count = _node_count()
|
|
74
|
+
if db_count is None:
|
|
75
|
+
return {"recovered": False, "log_points": 0, "db_points": None,
|
|
76
|
+
"reason": "graph unresponsive — recovery requires a live DB"}
|
|
77
|
+
if db_count > 0:
|
|
78
|
+
return {"recovered": False, "log_points": 0, "db_points": db_count,
|
|
79
|
+
"reason": "graph already has nodes — no rebuild"}
|
|
80
|
+
|
|
81
|
+
# db_count == 0: enumerate the adjacent logs (exactly one required).
|
|
82
|
+
try:
|
|
83
|
+
files = sorted(f for f in os.listdir(events_dir)
|
|
84
|
+
if f.endswith(".jsonl"))
|
|
85
|
+
except OSError as e:
|
|
86
|
+
return {"recovered": False, "log_points": 0, "db_points": 0,
|
|
87
|
+
"reason": f"event-log dir unreadable: {e}"}
|
|
88
|
+
if not files:
|
|
89
|
+
return {"recovered": False, "log_points": 0, "db_points": 0,
|
|
90
|
+
"reason": "no JSONL event log present"}
|
|
91
|
+
if len(files) > 1:
|
|
92
|
+
return {"recovered": False, "log_points": 0, "db_points": 0,
|
|
93
|
+
"reason": f"ambiguous: {len(files)} adjacent JSONL logs "
|
|
94
|
+
f"({', '.join(files[:3])}...) — refusing auto-rebuild"}
|
|
95
|
+
|
|
96
|
+
# Parse the single log, tolerating a torn trailing line.
|
|
97
|
+
log_path = os.path.join(events_dir, files[0])
|
|
98
|
+
events: list[dict] = []
|
|
99
|
+
torn = 0
|
|
100
|
+
try:
|
|
101
|
+
with open(log_path, encoding="utf-8") as fh:
|
|
102
|
+
for line in fh:
|
|
103
|
+
line = line.strip()
|
|
104
|
+
if not line:
|
|
105
|
+
continue
|
|
106
|
+
try:
|
|
107
|
+
events.append(_json.loads(line))
|
|
108
|
+
except Exception:
|
|
109
|
+
torn += 1
|
|
110
|
+
except OSError as e:
|
|
111
|
+
return {"recovered": False, "log_points": 0, "db_points": 0,
|
|
112
|
+
"reason": f"event log unreadable: {e}"}
|
|
113
|
+
if not events:
|
|
114
|
+
return {"recovered": False, "log_points": 0, "db_points": 0,
|
|
115
|
+
"reason": "event log empty or unreadable — nothing to recover"}
|
|
116
|
+
|
|
117
|
+
# Faithful replay via apply() (preserves context; restore uses the same
|
|
118
|
+
# path). Per-event guard: one bad event must not abort the whole recovery.
|
|
119
|
+
applied = 0
|
|
120
|
+
for ev in events:
|
|
121
|
+
try:
|
|
122
|
+
projection.apply(ev)
|
|
123
|
+
applied += 1
|
|
124
|
+
except Exception:
|
|
125
|
+
torn += 1
|
|
126
|
+
after = _node_count()
|
|
127
|
+
ok = applied > 0 and after is not None and after > 0
|
|
128
|
+
return {"recovered": ok, "log_points": len(events),
|
|
129
|
+
"db_points": after if after is not None else 0,
|
|
130
|
+
"reason": f"replayed {applied} events from {files[0]}"
|
|
131
|
+
+ (f" ({torn} skipped)" if torn else "") if ok
|
|
132
|
+
else "replay produced an empty graph"}
|
tortoise/crypto.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Encryption helpers for at-rest secrets (#499, #324 follow-up).
|
|
2
|
+
|
|
3
|
+
Fernet (AES-128-CBC + HMAC-SHA256) symmetric encryption for OAuth tokens
|
|
4
|
+
stored on the Team node. The key comes from TORTOISE_ENCRYPTION_KEY
|
|
5
|
+
(Fly.io secret). A missing/malformed key fails loudly — silent decryption
|
|
6
|
+
failure would corrupt tokens.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import os
|
|
12
|
+
|
|
13
|
+
from cryptography.fernet import Fernet, InvalidToken
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _get_key() -> bytes:
|
|
17
|
+
"""Return the Fernet key (32 url-safe base64 bytes) from env.
|
|
18
|
+
|
|
19
|
+
Raises RuntimeError if unset — fail-fast, never encrypt with a default.
|
|
20
|
+
"""
|
|
21
|
+
raw = os.environ.get("TORTOISE_ENCRYPTION_KEY")
|
|
22
|
+
if not raw:
|
|
23
|
+
raise RuntimeError(
|
|
24
|
+
"TORTOISE_ENCRYPTION_KEY not set — required for token encryption. "
|
|
25
|
+
"Generate with: python -c \"from cryptography.fernet import Fernet; "
|
|
26
|
+
"print(Fernet.generate_key().decode())\""
|
|
27
|
+
)
|
|
28
|
+
try:
|
|
29
|
+
return raw.encode() if isinstance(raw, str) else raw
|
|
30
|
+
except Exception as e:
|
|
31
|
+
raise RuntimeError(f"Invalid TORTOISE_ENCRYPTION_KEY: {e}")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def encrypt_token(token: str) -> str:
|
|
35
|
+
"""Encrypt a secret at rest. Returns url-safe base64 string."""
|
|
36
|
+
if token is None:
|
|
37
|
+
raise ValueError("Cannot encrypt None")
|
|
38
|
+
f = Fernet(_get_key())
|
|
39
|
+
return f.encrypt(token.encode("utf-8")).decode()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def decrypt_token(encrypted: str) -> str:
|
|
43
|
+
"""Decrypt a stored secret. Raises ValueError on tamper/malformed input."""
|
|
44
|
+
if not encrypted:
|
|
45
|
+
raise ValueError("Cannot decrypt empty ciphertext")
|
|
46
|
+
f = Fernet(_get_key())
|
|
47
|
+
try:
|
|
48
|
+
return f.decrypt(encrypted.encode("utf-8")).decode("utf-8")
|
|
49
|
+
except InvalidToken as e:
|
|
50
|
+
raise ValueError(f"Decryption failed — token tampered or wrong key: {e}")
|
|
51
|
+
except Exception as e:
|
|
52
|
+
raise ValueError(f"Decryption failed: {e}")
|
tortoise/deployment.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""P1-8 #6978: Deployment helpers — serve + health check."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
_start_time = time.monotonic()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def serve():
|
|
11
|
+
"""Tortoise MCP server entry point (console script `tortoise-serve`).
|
|
12
|
+
|
|
13
|
+
`tortoise-serve` → stdio MCP server (kept for scripting).
|
|
14
|
+
`tortoise-serve http [--host] [--port] [--api-key]` → self-host daemon
|
|
15
|
+
(T1.3, #338) — flags override env.
|
|
16
|
+
"""
|
|
17
|
+
import sys
|
|
18
|
+
|
|
19
|
+
if sys.argv[1:2] == ["http"]:
|
|
20
|
+
sys.argv.pop(1)
|
|
21
|
+
serve_http()
|
|
22
|
+
return
|
|
23
|
+
from tortoise.mcp_server import main
|
|
24
|
+
main()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def serve_http():
|
|
28
|
+
"""Start the self-host daemon over HTTP (MCP Streamable HTTP + /health).
|
|
29
|
+
|
|
30
|
+
CLI flags override env vars (T1.3 pin, #338):
|
|
31
|
+
tortoise-serve http [--host HOST] [--port PORT] [--api-key KEY]
|
|
32
|
+
"""
|
|
33
|
+
import os
|
|
34
|
+
|
|
35
|
+
import uvicorn
|
|
36
|
+
|
|
37
|
+
parser = argparse.ArgumentParser(prog="tortoise-serve http")
|
|
38
|
+
parser.add_argument("--host", default=None)
|
|
39
|
+
parser.add_argument("--port", type=int, default=None)
|
|
40
|
+
parser.add_argument("--api-key", default=None)
|
|
41
|
+
args = parser.parse_args()
|
|
42
|
+
|
|
43
|
+
# CLI flags override env BEFORE the app module is imported/built so the
|
|
44
|
+
# module-level app is constructed with the effective configuration.
|
|
45
|
+
if args.api_key is not None:
|
|
46
|
+
os.environ["TORTOISE_API_KEY"] = args.api_key
|
|
47
|
+
|
|
48
|
+
from tortoise import selfhost
|
|
49
|
+
|
|
50
|
+
host = args.host or selfhost.HOST
|
|
51
|
+
port = args.port or selfhost.PORT
|
|
52
|
+
uvicorn.run(selfhost.app, host=host, port=port)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def health(db=None) -> dict:
|
|
56
|
+
"""Health check — verifies FalkorDB connectivity."""
|
|
57
|
+
try:
|
|
58
|
+
if db is not None:
|
|
59
|
+
db.select_graph("tortoise").query("MATCH (n) RETURN count(n) LIMIT 1")
|
|
60
|
+
return {"status": "ok", "uptime": time.monotonic() - _start_time}
|
|
61
|
+
except Exception as e:
|
|
62
|
+
return {"status": "error", "error": str(e)}
|