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
@@ -0,0 +1,22 @@
1
+ """
2
+ DEPRECATED — This file is no longer in use.
3
+
4
+ Authentication for the Tortoise Hosted API has been consolidated into
5
+ hosted_api.py's inline `get_current_team` FastAPI dependency.
6
+
7
+ The AuthMiddleware and RequestIDMiddleware defined here were never wired
8
+ into hosted_api.py and are dead code. They have been removed as part of
9
+ issue #7837.
10
+
11
+ TODO: The inline `get_current_team` dependency in hosted_api.py is
12
+ missing the `last_used_at` tracking that was present in the old
13
+ AuthMiddleware here. Add the following after team resolution in
14
+ hosted_api.py's get_current_team:
15
+
16
+ sdk._get_proj().g.query(
17
+ "MATCH (k:APIKey {id: $id}) SET k.last_used_at = datetime()",
18
+ params={"id": key_id},
19
+ )
20
+
21
+ Without this, API key last-used timestamps are not being updated.
22
+ """
@@ -0,0 +1,39 @@
1
+ """Idempotency — input-keyed, so a re-run doesn't duplicate the graph.
2
+
3
+ The dedup key is the *input*, not the output (an LLM extractor won't reproduce
4
+ identical output). Two regimes, unified by `IngestKey`:
5
+ - document / batch : key = content_hash(document)
6
+ - stream : key = (stream_id, offset_range)
7
+
8
+ The gate itself lives in EventAPI.begin_ingest, which scans prior IngestStarted
9
+ events for a matching (key, extractor_version).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+
15
+ from .ids import content_hash
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class IngestKey:
20
+ kind: str # "document" | "stream"
21
+ value: str
22
+
23
+ def as_dict(self) -> dict:
24
+ return {"kind": self.kind, "value": self.value}
25
+
26
+
27
+ def document_key(text: str) -> IngestKey:
28
+ return IngestKey("document", content_hash(text))
29
+
30
+
31
+ def stream_key(stream_id: str, start: int, end: int) -> IngestKey:
32
+ return IngestKey("stream", f"{stream_id}:{start}-{end}")
33
+
34
+
35
+ @dataclass
36
+ class IngestResult:
37
+ run_id: str | None
38
+ skip: bool
39
+ reason: str = ""
tortoise/ids.py ADDED
@@ -0,0 +1,23 @@
1
+ """Minimal ID generation — ULID-style time-sortable unique IDs."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import time
6
+ import uuid
7
+
8
+
9
+ def ulid() -> str:
10
+ """Return a time-sortable unique ID: <timestamp-hex>-<uuid>."""
11
+ ts = hex(int(time.time() * 1000))[2:]
12
+ return f"{ts}-{uuid.uuid4().hex[:12]}"
13
+
14
+
15
+ def content_hash(text: str) -> str:
16
+ """SHA-256 hex digest of text — used for idempotency keys."""
17
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
18
+
19
+
20
+ def now_iso() -> str:
21
+ """Current UTC time as ISO 8601 string."""
22
+ from datetime import datetime, timezone
23
+ return datetime.now(timezone.utc).isoformat()
@@ -0,0 +1,129 @@
1
+ """GitHub issues/PRs → Tortoise Points indexer (#499).
2
+
3
+ Fetches issues and PRs from a GitHub org via REST API and creates Points
4
+ (kind="observation", source="github") in the team's graph. Rate-limit aware
5
+ (exponential backoff on 429), paginated, idempotent (dedup by github_url),
6
+ and truncates oversized bodies.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import logging
12
+ import time
13
+ from typing import Any
14
+
15
+ import httpx
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ _GITHUB_API = "https://api.github.com"
20
+ _MAX_BODY_CHARS = 5000
21
+ _MAX_ITEMS_PER_RUN = 500
22
+
23
+ class GitHubIndexer:
24
+ """Background indexer: org issues/PRs → Points in a team graph."""
25
+
26
+ def __init__(self, token: str, httpx_client: httpx.AsyncClient | None = None):
27
+ self._token = token
28
+ self._client = httpx_client
29
+
30
+ async def _get_client(self) -> httpx.AsyncClient:
31
+ if self._client is None:
32
+ self._client = httpx.AsyncClient(timeout=20)
33
+ return self._client
34
+
35
+ async def _close(self) -> None:
36
+ if self._client is not None and not self._client.is_closed:
37
+ await self._client.aclose()
38
+ self._client = None
39
+
40
+ async def _get(self, client: httpx.AsyncClient, url: str) -> httpx.Response | None:
41
+ """GET with rate-limit aware retry (exponential backoff on 429)."""
42
+ headers = {"Authorization": f"Bearer {self._token}",
43
+ "Accept": "application/vnd.github+json"}
44
+ for attempt in range(4):
45
+ try:
46
+ r = await client.get(url, headers=headers)
47
+ except httpx.HTTPError as e:
48
+ logger.warning("GitHub request failed (%s): %s", url, e)
49
+ await asyncio.sleep(2 ** attempt)
50
+ continue
51
+ if r.status_code == 429:
52
+ retry_after = int(r.headers.get("Retry-After", 2 ** attempt))
53
+ await asyncio.sleep(retry_after)
54
+ continue
55
+ if r.status_code >= 500:
56
+ await asyncio.sleep(2 ** attempt)
57
+ continue
58
+ return r
59
+ return None
60
+
61
+ async def _resolve_repos(self, client: httpx.AsyncClient, org: str) -> list[str]:
62
+ """Resolve repo names for an org (try org, fall back to user)."""
63
+ for kind in ("orgs", "users"):
64
+ r = await self._get(client, f"{_GITHUB_API}/{kind}/{org}/repos?per_page=100")
65
+ if r is not None and r.status_code == 200:
66
+ return [repo["full_name"] for repo in r.json()]
67
+ return []
68
+
69
+ async def _fetch_items(self, client: httpx.AsyncClient, repo: str) -> list[dict]:
70
+ """Fetch issues + PRs for a repo (paginated)."""
71
+ items: list[dict] = []
72
+ url = f"{_GITHUB_API}/repos/{repo}/issues?state=all&per_page=100"
73
+ while url and len(items) < _MAX_ITEMS_PER_RUN:
74
+ r = await self._get(client, url)
75
+ if r is None or r.status_code != 200:
76
+ break
77
+ batch = r.json()
78
+ # The issues endpoint includes PRs (pull_request key present)
79
+ items.extend(batch)
80
+ # Pagination via Link header rel="next"
81
+ link = r.headers.get("Link", "")
82
+ next_url = None
83
+ for part in link.split(","):
84
+ if 'rel="next"' in part:
85
+ next_url = part[part.index("<") + 1:part.index(">")]
86
+ break
87
+ url = next_url
88
+ return items[: _MAX_ITEMS_PER_RUN]
89
+
90
+ async def index_issues(self, sdk, org: str, repo: str | None = None) -> dict:
91
+ """Index issues/PRs from an org into the SDK's team graph.
92
+
93
+ Returns {points_created, repos_processed, errors, total_fetched}.
94
+ Idempotent: SDK create_point dedups by content hash — re-running with
95
+ unchanged issue content produces no new Points (same content hash).
96
+ Changed issues (edited title/body) create updated Points, which is
97
+ the desired behavior (each state is a distinct memory). github_url is
98
+ stored in props for traceability, not used for dedup.
99
+ """
100
+ client = await self._get_client()
101
+ errors: list[str] = []
102
+ repos = [org + "/" + repo] if repo else await self._resolve_repos(client, org)
103
+ points_created = 0
104
+ total_fetched = 0
105
+ for repo_name in repos:
106
+ try:
107
+ items = await self._fetch_items(client, repo_name)
108
+ except Exception as e: # noqa: BLE001
109
+ errors.append(f"{repo_name}: {e}")
110
+ continue
111
+ for item in items:
112
+ body = (item.get("body") or "")[:_MAX_BODY_CHARS]
113
+ title = (item.get("title") or "")[:_MAX_BODY_CHARS]
114
+ url = item.get("html_url") or ""
115
+ content = f"[{repo_name}] {title}\n\n{body}"[: _MAX_BODY_CHARS * 2]
116
+ props = {"source": "github", "github_url": url,
117
+ "github_repo": repo_name,
118
+ "github_state": item.get("state") or "open",
119
+ "github_number": item.get("number")}
120
+ try:
121
+ sdk.create_point(kind="observation", content=content,
122
+ authoredBy="github-indexer", props=props)
123
+ points_created += 1
124
+ except Exception as e: # noqa: BLE001
125
+ errors.append(f"{repo_name}#{item.get('number')}: {e}")
126
+ total_fetched += 1
127
+ await self._close()
128
+ return {"points_created": points_created, "repos_processed": len(repos),
129
+ "errors": errors, "total_fetched": total_fetched}