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,74 @@
|
|
|
1
|
+
"""Connector loader — reads config/connector_manifest.yaml, instantiates connectors."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import importlib
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger(__name__)
|
|
11
|
+
|
|
12
|
+
# Fields that should only be set via environment variables, never in YAML (#324)
|
|
13
|
+
_SECRET_FIELDS = {
|
|
14
|
+
"token", "signing_secret", "api_key", "webhook_secret",
|
|
15
|
+
"supabase_key", "supabase_service_key", "service_role_key",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def load_connectors(
|
|
20
|
+
manifest_path: str | Path | None = None,
|
|
21
|
+
api=None,
|
|
22
|
+
) -> dict[str, Any]:
|
|
23
|
+
"""Load and instantiate active connectors from manifest.
|
|
24
|
+
|
|
25
|
+
Returns {connector_key: connector_instance}.
|
|
26
|
+
"""
|
|
27
|
+
if manifest_path is None:
|
|
28
|
+
manifest_path = Path(__file__).parent.parent / "config" / "connector_manifest.yaml"
|
|
29
|
+
else:
|
|
30
|
+
manifest_path = Path(manifest_path)
|
|
31
|
+
|
|
32
|
+
if not manifest_path.exists():
|
|
33
|
+
return {}
|
|
34
|
+
|
|
35
|
+
import yaml
|
|
36
|
+
with open(manifest_path) as f:
|
|
37
|
+
data = yaml.safe_load(f) or {}
|
|
38
|
+
|
|
39
|
+
connectors: dict[str, Any] = {}
|
|
40
|
+
for key, cfg in (data.get("connectors") or {}).items():
|
|
41
|
+
if not cfg.get("active", True):
|
|
42
|
+
continue
|
|
43
|
+
|
|
44
|
+
config = cfg.get("config", {})
|
|
45
|
+
|
|
46
|
+
# Strip plaintext secrets from YAML config, warn if any found (#324)
|
|
47
|
+
plaintext_found = []
|
|
48
|
+
for field in _SECRET_FIELDS:
|
|
49
|
+
if config.get(field) and config[field] != "":
|
|
50
|
+
plaintext_found.append(field)
|
|
51
|
+
if plaintext_found:
|
|
52
|
+
logger.warning(
|
|
53
|
+
"Connector '%s' has plaintext secrets in YAML config: %s. "
|
|
54
|
+
"These will be ignored — use environment variables instead. "
|
|
55
|
+
"See issue #324 for migration details.",
|
|
56
|
+
key,
|
|
57
|
+
", ".join(plaintext_found),
|
|
58
|
+
)
|
|
59
|
+
# Strip the plaintext values so constructors must use env vars
|
|
60
|
+
for field in plaintext_found:
|
|
61
|
+
config[field] = ""
|
|
62
|
+
|
|
63
|
+
mod = importlib.import_module(cfg["module"])
|
|
64
|
+
cls = getattr(mod, cfg["class"])
|
|
65
|
+
instance = cls(config=config, api=api)
|
|
66
|
+
|
|
67
|
+
# Check for env-var config overrides
|
|
68
|
+
repo_env = os.environ.get("GITHUB_REPO")
|
|
69
|
+
if repo_env and hasattr(instance, "repo"):
|
|
70
|
+
instance.repo = repo_env
|
|
71
|
+
|
|
72
|
+
connectors[key] = instance
|
|
73
|
+
|
|
74
|
+
return connectors
|
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""P1-7 #6976 / GAP-11 #6998: GitHub connector — poll + webhook.
|
|
2
|
+
|
|
3
|
+
Zero Python deps. Uses `gh` CLI for polling + stdlib http.server for webhook.
|
|
4
|
+
Maps issues/PRs → 4-entity chain per ONTOLOGY_v2.5 §1.1:
|
|
5
|
+
Source (github_issue) → Object (pm:issue) → Event (pm:cardCreated)
|
|
6
|
+
+ Subject (naturalPerson for author/assignees)
|
|
7
|
+
PM domain extension kinds: pm:issue, pm:card, pm:cardCreated, pm:cardCompleted.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import json
|
|
12
|
+
import hmac
|
|
13
|
+
import hashlib
|
|
14
|
+
import logging
|
|
15
|
+
import os
|
|
16
|
+
import subprocess
|
|
17
|
+
import threading
|
|
18
|
+
from http.server import HTTPServer, BaseHTTPRequestHandler
|
|
19
|
+
from typing import Any, Callable
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _now_iso() -> str:
|
|
25
|
+
from datetime import datetime, timezone
|
|
26
|
+
return datetime.now(timezone.utc).isoformat()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _extract_label_prefix(labels: list[str], prefix: str) -> str | None:
|
|
30
|
+
"""Extract value after a label prefix. E.g., _extract_label_prefix(['complexity:micro'], 'complexity:') -> 'micro'."""
|
|
31
|
+
for label in labels:
|
|
32
|
+
if label.startswith(prefix):
|
|
33
|
+
return label[len(prefix):]
|
|
34
|
+
return None
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class GitHubConnector:
|
|
38
|
+
"""Poll GitHub issues/PRs via `gh` CLI + optional webhook server."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, config: dict[str, Any] | None = None, api=None):
|
|
41
|
+
cfg = config or {}
|
|
42
|
+
self.repo = cfg.get("repo", "")
|
|
43
|
+
self.state = cfg.get("state", "open")
|
|
44
|
+
self.limit = int(cfg.get("limit", 100))
|
|
45
|
+
self.webhook_port = int(cfg.get("webhook_port", 0))
|
|
46
|
+
# Env var takes precedence over config for webhook_secret (#324)
|
|
47
|
+
env_secret = os.environ.get("GITHUB_WEBHOOK_SECRET")
|
|
48
|
+
self.webhook_secret = (
|
|
49
|
+
env_secret if env_secret is not None else cfg.get("webhook_secret", "")
|
|
50
|
+
)
|
|
51
|
+
self.api = api
|
|
52
|
+
self._server: HTTPServer | None = None
|
|
53
|
+
self._thread: threading.Thread | None = None
|
|
54
|
+
self._routing = self._load_routing()
|
|
55
|
+
|
|
56
|
+
def _load_routing(self) -> dict:
|
|
57
|
+
"""Load entity routing config (config/routing.yaml)."""
|
|
58
|
+
import yaml
|
|
59
|
+
from pathlib import Path
|
|
60
|
+
path = Path(__file__).resolve().parent.parent.parent / "config" / "routing.yaml"
|
|
61
|
+
if path.exists():
|
|
62
|
+
return yaml.safe_load(path.read_text()) or {}
|
|
63
|
+
return {}
|
|
64
|
+
|
|
65
|
+
def _route_issue(self, labels: list[str]) -> dict:
|
|
66
|
+
"""Determine team + role for an issue based on routing config."""
|
|
67
|
+
routing = self._routing
|
|
68
|
+
label_map = routing.get("label_routing", {})
|
|
69
|
+
repo_routing = routing.get("repo_routing", {}).get(self.repo, {})
|
|
70
|
+
default_team = repo_routing.get("default_team", "")
|
|
71
|
+
product = repo_routing.get("product", "")
|
|
72
|
+
fallback = routing.get("attribution_fallback", "default_team")
|
|
73
|
+
team = ""
|
|
74
|
+
role = "product-implementer"
|
|
75
|
+
for label in labels:
|
|
76
|
+
if label in label_map:
|
|
77
|
+
cfg = label_map[label]
|
|
78
|
+
if cfg.get("team"): team = cfg["team"]
|
|
79
|
+
if cfg.get("role"): role = cfg["role"]
|
|
80
|
+
if not team:
|
|
81
|
+
team = default_team
|
|
82
|
+
if not team and fallback != "skip":
|
|
83
|
+
team = "default" if fallback == "default_team" else ""
|
|
84
|
+
return {"team": team, "role": role, "product": product}
|
|
85
|
+
|
|
86
|
+
# ── Polling ─────────────────────────────────────────────────
|
|
87
|
+
|
|
88
|
+
def poll(self) -> list[dict]:
|
|
89
|
+
"""Fetch issues + PRs via `gh` CLI → EventRecorded dicts."""
|
|
90
|
+
if not self.repo:
|
|
91
|
+
return []
|
|
92
|
+
events: list[dict] = []
|
|
93
|
+
events.extend(self._poll_issues())
|
|
94
|
+
events.extend(self._poll_prs())
|
|
95
|
+
return events
|
|
96
|
+
|
|
97
|
+
def poll_raw_issues(self) -> list[dict]:
|
|
98
|
+
"""Fetch raw issue dicts from GitHub API (for entity extraction)."""
|
|
99
|
+
if not self.repo:
|
|
100
|
+
return []
|
|
101
|
+
result = subprocess.run(
|
|
102
|
+
[
|
|
103
|
+
"gh", "issue", "list",
|
|
104
|
+
"--repo", self.repo,
|
|
105
|
+
"--state", self.state,
|
|
106
|
+
"--limit", str(self.limit),
|
|
107
|
+
"--json", "number,title,state,createdAt,closedAt,url,"
|
|
108
|
+
"labels,assignees,author,milestone",
|
|
109
|
+
],
|
|
110
|
+
capture_output=True, text=True, timeout=30,
|
|
111
|
+
)
|
|
112
|
+
if result.returncode != 0:
|
|
113
|
+
return []
|
|
114
|
+
return json.loads(result.stdout)
|
|
115
|
+
|
|
116
|
+
def _poll_issues(self) -> list[dict]:
|
|
117
|
+
result = subprocess.run(
|
|
118
|
+
[
|
|
119
|
+
"gh", "issue", "list",
|
|
120
|
+
"--repo", self.repo,
|
|
121
|
+
"--state", self.state,
|
|
122
|
+
"--limit", str(self.limit),
|
|
123
|
+
"--json", "number,title,state,createdAt,closedAt,url",
|
|
124
|
+
],
|
|
125
|
+
capture_output=True, text=True, timeout=30,
|
|
126
|
+
)
|
|
127
|
+
if result.returncode != 0:
|
|
128
|
+
return []
|
|
129
|
+
return [ev for issue in json.loads(result.stdout)
|
|
130
|
+
if (ev := self._issue_to_event(issue))]
|
|
131
|
+
|
|
132
|
+
def _poll_prs(self) -> list[dict]:
|
|
133
|
+
result = subprocess.run(
|
|
134
|
+
[
|
|
135
|
+
"gh", "pr", "list",
|
|
136
|
+
"--repo", self.repo,
|
|
137
|
+
"--state", self.state,
|
|
138
|
+
"--limit", str(self.limit),
|
|
139
|
+
"--json", "number,title,state,createdAt,closedAt,mergedAt,url",
|
|
140
|
+
],
|
|
141
|
+
capture_output=True, text=True, timeout=30,
|
|
142
|
+
)
|
|
143
|
+
if result.returncode != 0:
|
|
144
|
+
return []
|
|
145
|
+
return [ev for pr in json.loads(result.stdout)
|
|
146
|
+
if (ev := self._pr_to_event(pr))]
|
|
147
|
+
|
|
148
|
+
# ── Entity extraction (ONTOLOGY_v2.5 §1.1, PM domain extension) ────
|
|
149
|
+
|
|
150
|
+
def _issue_to_entities(self, issue: dict) -> dict | None:
|
|
151
|
+
"""Map GitHub issue → entity chain.
|
|
152
|
+
|
|
153
|
+
Returns dict with: object (ObjectRegistered), event (EventRecorded),
|
|
154
|
+
subjects (SubjectAdded list), about_edges.
|
|
155
|
+
Per ONTOLOGY_v2.5 §1.1: Object (pm:issue), Subject (naturalPerson).
|
|
156
|
+
PM domain extension: packs/project-management/manifest.yaml.
|
|
157
|
+
"""
|
|
158
|
+
number = issue.get("number")
|
|
159
|
+
title = issue.get("title", "")
|
|
160
|
+
if not title or not number:
|
|
161
|
+
return None
|
|
162
|
+
|
|
163
|
+
state = issue.get("state", "")
|
|
164
|
+
created_at = issue.get("createdAt", "")
|
|
165
|
+
closed_at = issue.get("closedAt", "")
|
|
166
|
+
url = issue.get("url", "")
|
|
167
|
+
labels = [l.get("name", "") for l in (issue.get("labels") or [])]
|
|
168
|
+
complexity = _extract_label_prefix(labels, "complexity:") or "standard"
|
|
169
|
+
ux_rating = _extract_label_prefix(labels, "ux:") or ""
|
|
170
|
+
assignees = [a.get("login", "") for a in (issue.get("assignees") or [])]
|
|
171
|
+
author = (issue.get("author") or {}).get("login", "") # P0: handle null author
|
|
172
|
+
milestone = (issue.get("milestone") or {}).get("title", "")
|
|
173
|
+
|
|
174
|
+
entity_id = f"github-issue-{self.repo}-{number}"
|
|
175
|
+
|
|
176
|
+
# Route to team + role based on labels + repo config
|
|
177
|
+
route = self._route_issue(labels)
|
|
178
|
+
|
|
179
|
+
# Object — persisted entity (PM domain extension, ONTOLOGY_v2.5 §1.1)
|
|
180
|
+
obj = {
|
|
181
|
+
"type": "ObjectRegistered",
|
|
182
|
+
"id": entity_id,
|
|
183
|
+
"name": f"{self.repo}#{number}",
|
|
184
|
+
"object_kind": "pm:issue",
|
|
185
|
+
"title": title,
|
|
186
|
+
"url": url,
|
|
187
|
+
"createdAt": created_at,
|
|
188
|
+
"routed_team": route["team"],
|
|
189
|
+
"routed_role": route["role"],
|
|
190
|
+
"routed_product": route["product"],
|
|
191
|
+
"complexity": complexity,
|
|
192
|
+
"ux_rating": ux_rating,
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
# Event — temporal occurrence (PM domain extension)
|
|
196
|
+
event_kind = "pm:cardCompleted" if state == "closed" else "pm:cardCreated"
|
|
197
|
+
event = {
|
|
198
|
+
"type": "EventRecorded",
|
|
199
|
+
"eventId": f"{entity_id}-created",
|
|
200
|
+
"eventKind": event_kind,
|
|
201
|
+
"subject": f"github-user:{author}" if author else f"repo:{self.repo}",
|
|
202
|
+
"object": entity_id,
|
|
203
|
+
"startedAt": created_at,
|
|
204
|
+
"endedAt": closed_at if state == "closed" else None,
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
# Subjects — people involved (ONTOLOGY_v2.5 §1.1 subjectKind)
|
|
208
|
+
subjects = []
|
|
209
|
+
seen = set()
|
|
210
|
+
for login in [author] + assignees:
|
|
211
|
+
if login and login not in seen:
|
|
212
|
+
seen.add(login)
|
|
213
|
+
subjects.append({
|
|
214
|
+
"type": "SubjectAdded",
|
|
215
|
+
"id": f"github-user:{login}",
|
|
216
|
+
"name": login,
|
|
217
|
+
"subject_kind": "naturalPerson",
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
# aboutSubject edges — Object → Subject (ONTOLOGY_v2.5 §2.2)
|
|
221
|
+
about_subjects = [s["id"] for s in subjects]
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
"object": obj,
|
|
225
|
+
"event": event,
|
|
226
|
+
"subjects": subjects,
|
|
227
|
+
"aboutSubjects": about_subjects,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
def ingest(self, proj) -> int:
|
|
231
|
+
"""Poll + apply to projection. Returns count of applied events.
|
|
232
|
+
Issues get entity chain: Object (pm:issue) + Event + Subjects + aboutSubject edges.
|
|
233
|
+
PRs get event-only (existing behavior).
|
|
234
|
+
"""
|
|
235
|
+
events = self.poll()
|
|
236
|
+
count = 0
|
|
237
|
+
for ev in events:
|
|
238
|
+
proj.apply(ev)
|
|
239
|
+
count += 1
|
|
240
|
+
|
|
241
|
+
# Entity extraction for issues (ONTOLOGY_v2.5 §1.1, PM domain extension)
|
|
242
|
+
try:
|
|
243
|
+
raw_issues = self.poll_raw_issues()
|
|
244
|
+
except Exception:
|
|
245
|
+
raw_issues = [] # ponytail: gh CLI may fail, skip entity extraction
|
|
246
|
+
|
|
247
|
+
for issue in raw_issues:
|
|
248
|
+
entities = self._issue_to_entities(issue)
|
|
249
|
+
if not entities:
|
|
250
|
+
continue
|
|
251
|
+
|
|
252
|
+
# Apply Object (ObjectRegistered → FalkorDB)
|
|
253
|
+
if entities.get("object"):
|
|
254
|
+
proj.apply(entities["object"])
|
|
255
|
+
# Set routing properties (not handled by projection's _upsert_object)
|
|
256
|
+
obj = entities["object"]
|
|
257
|
+
proj.g.query(
|
|
258
|
+
"MATCH (o:Object {id: $id}) "
|
|
259
|
+
"SET o.routed_team = $team, o.routed_role = $role, o.routed_product = $product, "
|
|
260
|
+
"o.complexity = $complexity, o.ux_rating = $ux_rating",
|
|
261
|
+
params={
|
|
262
|
+
"id": obj.get("id"),
|
|
263
|
+
"team": obj.get("routed_team", ""),
|
|
264
|
+
"role": obj.get("routed_role", ""),
|
|
265
|
+
"product": obj.get("routed_product", ""),
|
|
266
|
+
"complexity": obj.get("complexity", "standard"),
|
|
267
|
+
"ux_rating": obj.get("ux_rating", ""),
|
|
268
|
+
},
|
|
269
|
+
)
|
|
270
|
+
|
|
271
|
+
# Apply Event (EventRecorded → FalkorDB)
|
|
272
|
+
if entities.get("event"):
|
|
273
|
+
proj.apply(entities["event"])
|
|
274
|
+
|
|
275
|
+
# Apply Subjects (SubjectAdded → FalkorDB)
|
|
276
|
+
for subj in entities.get("subjects", []):
|
|
277
|
+
proj.apply(subj)
|
|
278
|
+
|
|
279
|
+
# aboutSubject edges — Object → Subject (ONTOLOGY_v2.5 §2.2)
|
|
280
|
+
obj_id = entities.get("object", {}).get("id", "")
|
|
281
|
+
for sid in entities.get("aboutSubjects", []):
|
|
282
|
+
if obj_id and sid:
|
|
283
|
+
proj.g.query(
|
|
284
|
+
"MATCH (o:Object {id: $oid}) "
|
|
285
|
+
"MATCH (s:Subject {id: $sid}) "
|
|
286
|
+
"MERGE (o)-[:aboutSubject]->(s)",
|
|
287
|
+
params={"oid": obj_id, "sid": sid},
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
count += 1
|
|
291
|
+
return count
|
|
292
|
+
|
|
293
|
+
# ── Webhook (GAP-11) ───────────────────────────────────────────
|
|
294
|
+
|
|
295
|
+
def start_webhook(self, on_event: Callable[[dict], None] | None = None) -> int:
|
|
296
|
+
"""Start webhook server on configured port. Returns port number.
|
|
297
|
+
Runs in a daemon thread; call stop_webhook() to shut down.
|
|
298
|
+
"""
|
|
299
|
+
if not self.webhook_port:
|
|
300
|
+
return 0
|
|
301
|
+
|
|
302
|
+
secret = self.webhook_secret.encode() if self.webhook_secret else None
|
|
303
|
+
connector = self # capture for handler closure
|
|
304
|
+
|
|
305
|
+
class Handler(BaseHTTPRequestHandler):
|
|
306
|
+
def do_POST(self):
|
|
307
|
+
length = int(self.headers.get("Content-Length", 0))
|
|
308
|
+
body = self.rfile.read(length)
|
|
309
|
+
sig = self.headers.get("X-Hub-Signature-256", "")
|
|
310
|
+
|
|
311
|
+
# Verify signature if secret configured
|
|
312
|
+
if secret and not _verify_sig(secret, sig, body):
|
|
313
|
+
self.send_response(403)
|
|
314
|
+
self.end_headers()
|
|
315
|
+
return
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
payload = json.loads(body)
|
|
319
|
+
except json.JSONDecodeError:
|
|
320
|
+
self.send_response(400)
|
|
321
|
+
self.end_headers()
|
|
322
|
+
return
|
|
323
|
+
|
|
324
|
+
event_type = self.headers.get("X-GitHub-Event", "")
|
|
325
|
+
ev = connector._webhook_to_event(event_type, payload)
|
|
326
|
+
if ev:
|
|
327
|
+
if on_event:
|
|
328
|
+
on_event(ev)
|
|
329
|
+
if connector.api:
|
|
330
|
+
connector.api.get_proj().apply(ev)
|
|
331
|
+
self.send_response(200)
|
|
332
|
+
self.end_headers()
|
|
333
|
+
|
|
334
|
+
def log_message(self, format, *args):
|
|
335
|
+
pass # ponytail: suppress HTTP log noise
|
|
336
|
+
|
|
337
|
+
self._server = HTTPServer(("127.0.0.1", self.webhook_port), Handler)
|
|
338
|
+
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
339
|
+
self._thread.start()
|
|
340
|
+
return self.webhook_port
|
|
341
|
+
|
|
342
|
+
def stop_webhook(self) -> None:
|
|
343
|
+
if self._server:
|
|
344
|
+
self._server.shutdown()
|
|
345
|
+
self._server = None
|
|
346
|
+
self._thread = None
|
|
347
|
+
|
|
348
|
+
# ── Event mapping ──────────────────────────────────────────────
|
|
349
|
+
|
|
350
|
+
def _issue_to_event(self, issue: dict) -> dict | None:
|
|
351
|
+
number = issue.get("number")
|
|
352
|
+
title = issue.get("title", "")
|
|
353
|
+
if not title or not number:
|
|
354
|
+
return None
|
|
355
|
+
|
|
356
|
+
state = issue.get("state", "")
|
|
357
|
+
created_at = issue.get("createdAt", "")
|
|
358
|
+
closed_at = issue.get("closedAt", "")
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
"type": "EventRecorded",
|
|
362
|
+
"eventId": f"github-issue-{self.repo}-{number}",
|
|
363
|
+
"eventKind": f"github.issue.{state}",
|
|
364
|
+
"subject": f"issue:{self.repo}#{number}",
|
|
365
|
+
"object": title,
|
|
366
|
+
"startedAt": created_at,
|
|
367
|
+
"endedAt": closed_at if state == "closed" else None,
|
|
368
|
+
"source": f"github:{self.repo}",
|
|
369
|
+
"sourceKind": "github_issue", "sourceKind": "github_issue",
|
|
370
|
+
"participants": [],
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
def _pr_to_event(self, pr: dict) -> dict | None:
|
|
374
|
+
number = pr.get("number")
|
|
375
|
+
title = pr.get("title", "")
|
|
376
|
+
if not title or not number:
|
|
377
|
+
return None
|
|
378
|
+
|
|
379
|
+
state = pr.get("state", "")
|
|
380
|
+
merged_at = pr.get("mergedAt")
|
|
381
|
+
created_at = pr.get("createdAt", "")
|
|
382
|
+
closed_at = pr.get("closedAt", "")
|
|
383
|
+
|
|
384
|
+
kind = "github.pr.merged" if merged_at else f"github.pr.{state}"
|
|
385
|
+
|
|
386
|
+
return {
|
|
387
|
+
"type": "EventRecorded",
|
|
388
|
+
"eventId": f"github-pr-{self.repo}-{number}",
|
|
389
|
+
"eventKind": kind,
|
|
390
|
+
"subject": f"pr:{self.repo}#{number}",
|
|
391
|
+
"object": title,
|
|
392
|
+
"startedAt": created_at,
|
|
393
|
+
"endedAt": merged_at or (closed_at if state == "closed" else None),
|
|
394
|
+
"source": f"github:{self.repo}",
|
|
395
|
+
"sourceKind": "github_issue", "sourceKind": "github_issue",
|
|
396
|
+
"participants": [],
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
def _webhook_to_event(self, event_type: str, payload: dict) -> dict | None:
|
|
400
|
+
"""Map GitHub webhook event → EventRecorded."""
|
|
401
|
+
if event_type == "issues":
|
|
402
|
+
issue = payload.get("issue", {})
|
|
403
|
+
action = payload.get("action", "")
|
|
404
|
+
return self._issue_to_event({
|
|
405
|
+
"number": issue.get("number"),
|
|
406
|
+
"title": issue.get("title", ""),
|
|
407
|
+
"state": "closed" if action == "closed" else "open",
|
|
408
|
+
"createdAt": issue.get("created_at", ""),
|
|
409
|
+
"closedAt": issue.get("closed_at"),
|
|
410
|
+
"url": issue.get("html_url", ""),
|
|
411
|
+
})
|
|
412
|
+
if event_type == "pull_request":
|
|
413
|
+
pr = payload.get("pull_request", {})
|
|
414
|
+
action = payload.get("action", "")
|
|
415
|
+
return self._pr_to_event({
|
|
416
|
+
"number": pr.get("number"),
|
|
417
|
+
"title": pr.get("title", ""),
|
|
418
|
+
"state": "closed" if action == "closed" else "open",
|
|
419
|
+
"createdAt": pr.get("created_at", ""),
|
|
420
|
+
"closedAt": pr.get("closed_at"),
|
|
421
|
+
"mergedAt": pr.get("merged_at"),
|
|
422
|
+
"url": pr.get("html_url", ""),
|
|
423
|
+
})
|
|
424
|
+
return None
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _verify_sig(secret: bytes, header: str, body: bytes) -> bool:
|
|
428
|
+
"""Constant-time HMAC-SHA256 verification of webhook signature."""
|
|
429
|
+
if not header.startswith("sha256="):
|
|
430
|
+
return False
|
|
431
|
+
expected = hmac.new(secret, body, hashlib.sha256).hexdigest()
|
|
432
|
+
return hmac.compare_digest(f"sha256={expected}", header)
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""GitHub doc indexer — clone repo, generate frontmatter, extract into semantic graph.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
tortoise index github <url-or-path> [--branch main] [--enrich]
|
|
5
|
+
|
|
6
|
+
Walks all .md files, generates frontmatter for docs that lack it,
|
|
7
|
+
classifies document kind, extracts entities and claims into FalkorDB.
|
|
8
|
+
Content-hash idempotent — re-running skips unchanged files.
|
|
9
|
+
|
|
10
|
+
Integrates into onboarding: tortoise init detects git repo, offers indexing
|
|
11
|
+
as a background task.
|
|
12
|
+
"""
|
|
13
|
+
import hashlib
|
|
14
|
+
import os
|
|
15
|
+
import subprocess
|
|
16
|
+
import tempfile
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Optional
|
|
20
|
+
|
|
21
|
+
from tortoise.doc_store import DocStore
|
|
22
|
+
from tortoise.sdk import TortoiseSDK
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class GitHubDocIndexer:
|
|
26
|
+
"""Index markdown files from a GitHub repo or local directory.
|
|
27
|
+
|
|
28
|
+
Pipeline: clone/walk → generate frontmatter → classify → extract → ingest.
|
|
29
|
+
Idempotent via SHA-256 content hash.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, sdk: Optional[TortoiseSDK] = None):
|
|
33
|
+
import os
|
|
34
|
+
if sdk:
|
|
35
|
+
self.sdk = sdk
|
|
36
|
+
elif os.environ.get("TORTOISE_DB_URI") or os.environ.get("TORTOISE_DB_PATH"):
|
|
37
|
+
self.sdk = TortoiseSDK()
|
|
38
|
+
else:
|
|
39
|
+
raise ValueError(
|
|
40
|
+
"GitHubDocIndexer requires TORTOISE_DB_URI env var or an explicit SDK instance"
|
|
41
|
+
)
|
|
42
|
+
self._hashes: dict[str, str] = {} # path → sha256 for dedup
|
|
43
|
+
|
|
44
|
+
def index_repo(self, url_or_path: str, branch: str = "main",
|
|
45
|
+
enrich: bool = False) -> dict:
|
|
46
|
+
"""Index all markdown files from a GitHub repo or local directory.
|
|
47
|
+
|
|
48
|
+
Args:
|
|
49
|
+
url_or_path: GitHub URL or local directory path
|
|
50
|
+
branch: Git branch (only for remote repos)
|
|
51
|
+
enrich: Run LLM enrichment (requires API key)
|
|
52
|
+
|
|
53
|
+
Returns dict with stats: {files_found, files_indexed, files_skipped, errors}
|
|
54
|
+
"""
|
|
55
|
+
if os.path.isdir(url_or_path):
|
|
56
|
+
repo_path = url_or_path
|
|
57
|
+
is_temp = False
|
|
58
|
+
else:
|
|
59
|
+
repo_path = self._clone(url_or_path, branch)
|
|
60
|
+
is_temp = True
|
|
61
|
+
|
|
62
|
+
try:
|
|
63
|
+
return self._index_directory(repo_path, enrich)
|
|
64
|
+
finally:
|
|
65
|
+
if is_temp:
|
|
66
|
+
import shutil
|
|
67
|
+
shutil.rmtree(repo_path, ignore_errors=True)
|
|
68
|
+
|
|
69
|
+
def _clone(self, url: str, branch: str) -> str:
|
|
70
|
+
"""Clone a GitHub repo to a temp directory. Returns path."""
|
|
71
|
+
tmp = tempfile.mkdtemp(prefix="tortoise-repo-")
|
|
72
|
+
subprocess.run(
|
|
73
|
+
["git", "clone", "--depth", "1", "--branch", branch, url, tmp],
|
|
74
|
+
capture_output=True, timeout=120,
|
|
75
|
+
)
|
|
76
|
+
return tmp
|
|
77
|
+
|
|
78
|
+
def _index_directory(self, repo_path: str, enrich: bool = False) -> dict:
|
|
79
|
+
"""Walk directory, index all .md files. Returns stats."""
|
|
80
|
+
found = 0
|
|
81
|
+
indexed = 0
|
|
82
|
+
skipped = 0
|
|
83
|
+
errors = 0
|
|
84
|
+
|
|
85
|
+
for md_file in Path(repo_path).rglob("*.md"):
|
|
86
|
+
found += 1
|
|
87
|
+
try:
|
|
88
|
+
if self._should_skip(md_file):
|
|
89
|
+
skipped += 1
|
|
90
|
+
continue
|
|
91
|
+
|
|
92
|
+
self._index_file(md_file, enrich)
|
|
93
|
+
indexed += 1
|
|
94
|
+
except Exception as e:
|
|
95
|
+
errors += 1
|
|
96
|
+
print(f" ⚠️ {md_file}: {e}")
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
"files_found": found,
|
|
100
|
+
"files_indexed": indexed,
|
|
101
|
+
"files_skipped": skipped,
|
|
102
|
+
"errors": errors,
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
def _should_skip(self, path: Path) -> bool:
|
|
106
|
+
"""Skip if content unchanged (idempotent)."""
|
|
107
|
+
content = path.read_text()
|
|
108
|
+
chash = hashlib.sha256(content.encode()).hexdigest()
|
|
109
|
+
key = str(path)
|
|
110
|
+
if self._hashes.get(key) == chash:
|
|
111
|
+
return True
|
|
112
|
+
self._hashes[key] = chash
|
|
113
|
+
return False
|
|
114
|
+
|
|
115
|
+
def _index_file(self, path: Path, enrich: bool = False) -> None:
|
|
116
|
+
"""Run full pipeline on a single file: frontmatter → classify → extract → ingest."""
|
|
117
|
+
# 1. Generate frontmatter if missing
|
|
118
|
+
self._ensure_frontmatter(path)
|
|
119
|
+
|
|
120
|
+
# 2. Classify document kind
|
|
121
|
+
from tortoise.doc_classify import classify as classify_file
|
|
122
|
+
doc_kind = classify_file(str(path))
|
|
123
|
+
|
|
124
|
+
# 3. Extract entities and claims
|
|
125
|
+
from tortoise.extraction_pipeline import ExtractionPipeline
|
|
126
|
+
pipeline = ExtractionPipeline(self.sdk)
|
|
127
|
+
pipeline.process_file(str(path), doc_kind=doc_kind)
|
|
128
|
+
|
|
129
|
+
def _ensure_frontmatter(self, path: Path) -> None:
|
|
130
|
+
"""Generate frontmatter for files that lack it."""
|
|
131
|
+
content = path.read_text()
|
|
132
|
+
if content.startswith("---"):
|
|
133
|
+
return # Already has frontmatter
|
|
134
|
+
|
|
135
|
+
# Derive structural frontmatter from path
|
|
136
|
+
now = datetime.now(timezone.utc).strftime("%Y-%m-%d")
|
|
137
|
+
title = path.stem.replace("-", " ").replace("_", " ").title()
|
|
138
|
+
fm = f"""---
|
|
139
|
+
title: "{title}"
|
|
140
|
+
type: document
|
|
141
|
+
domain: capability
|
|
142
|
+
status: draft
|
|
143
|
+
created: {now}
|
|
144
|
+
---
|
|
145
|
+
"""
|
|
146
|
+
path.write_text(fm + content)
|