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,114 @@
1
+ """Shock propagation and confidence computation for FalkorProjection."""
2
+ from __future__ import annotations
3
+
4
+ from collections import deque
5
+
6
+
7
+ class _PropagationMixin:
8
+ """Mixin: shock propagation + confidence helper methods."""
9
+
10
+ def propagate_shock(self, epicenter_id: str, *, max_depth: int = 2,
11
+ damping: float = 0.5, threshold: float = 0.05
12
+ ) -> dict[str, tuple[float, float]]:
13
+ """BFS shock propagation through IMPL (supports) and NAND (contradicts)
14
+ edges. Ported from /Users/home/eldato/operations/memory/epistemic.py.
15
+
16
+ Each BFS step carries the parent's computed confidence into the child's
17
+ _compute_confidence — the parent signal blends with local edge-ratio
18
+ evidence BEFORE the inertia damping is applied. Without this, _compute_
19
+ confidence sees only static edge counts and the shock never flows."""
20
+ changed: dict[str, tuple[float, float]] = {}
21
+ visited: set[str] = set()
22
+
23
+ # Skip if epicenter is deprecated/superseded
24
+ status = self._node_status(epicenter_id)
25
+ if status and status != 'live':
26
+ return {}
27
+
28
+ queue: deque[tuple[str, int, float | None]] = deque(
29
+ [(epicenter_id, 0, None)]
30
+ )
31
+
32
+ while queue:
33
+ node_id, depth, parent_conf = queue.popleft()
34
+ if depth > max_depth or node_id in visited:
35
+ continue
36
+ visited.add(node_id)
37
+
38
+ old = self._confidence(node_id)
39
+ new = self._compute_confidence(node_id, parent_conf)
40
+ if depth > 0:
41
+ new = old * damping + new * (1 - damping)
42
+ new = round(new, 4)
43
+
44
+ if abs(new - old) > threshold:
45
+ self.g.query(
46
+ "MATCH (n:Point {id:$id}) SET n.confidence=$v",
47
+ params={"id": node_id, "v": new},
48
+ )
49
+ changed[node_id] = (old, new)
50
+
51
+ if depth < max_depth:
52
+ for nid in self._neighbors(node_id):
53
+ if nid not in visited:
54
+ queue.append((nid, depth + 1, new))
55
+
56
+ return changed
57
+
58
+ def _compute_confidence(self, node_id: str,
59
+ parent_confidence: float | None = None) -> float:
60
+ """Weighted confidence from neighbor beliefs, not just edge counts.
61
+
62
+ Each IMPL edge contributes the neighbor's current confidence;
63
+ each NAND edge contributes (1 - neighbor's confidence) — so a
64
+ confident contradiction hurts more than a tentative one. Default 0.5
65
+ when no edges or no neighbors have confidence set.
66
+ """
67
+ s_rows = self.g.query(
68
+ "MATCH (n:Point {id:$id})-[r:IMPL]-(m:Point) "
69
+ "RETURN coalesce(m.confidence, 0.5)",
70
+ params={"id": node_id},
71
+ ).result_set
72
+ c_rows = self.g.query(
73
+ "MATCH (n:Point {id:$id})-[r:NAND]-(m:Point) "
74
+ "RETURN coalesce(m.confidence, 0.5)",
75
+ params={"id": node_id},
76
+ ).result_set
77
+
78
+ s_weighted = sum(r[0] for r in s_rows)
79
+ c_weighted = sum(r[0] for r in c_rows)
80
+ total = s_weighted + c_weighted
81
+ base = s_weighted / total if total else 0.5
82
+ if parent_confidence is None:
83
+ return base
84
+ return base * 0.5 + parent_confidence * 0.5
85
+
86
+ def _confidence(self, node_id: str) -> float:
87
+ r = self.g.query(
88
+ "MATCH (n:Point {id:$id}) RETURN coalesce(n.confidence, 0.5)",
89
+ params={"id": node_id},
90
+ ).result_set
91
+ return float(r[0][0]) if r else 0.5
92
+
93
+ def _node_status(self, node_id: str) -> str | None:
94
+ """Return the status of a Point node, or None if not found."""
95
+ r = self.g.query(
96
+ "MATCH (n:Point {id:$id}) RETURN n.status",
97
+ params={"id": node_id},
98
+ ).result_set
99
+ return r[0][0] if r else None
100
+
101
+ def _neighbors(self, node_id: str) -> list[str]:
102
+ """All Points reachable via IMPL or NAND edges (both directions).
103
+
104
+ Hops through operator nodes: (claim)-[r]-(op:Point {is_operator:true})-[r2]-(other).
105
+ A point's neighbors are the other endpoints of any operator it participates in,
106
+ regardless of source/target role — this is what makes EP affected-set expansion
107
+ work for directional IMPL and bidirectional hasPart/NAND alike (#86).
108
+ """
109
+ rows = self.g.query(
110
+ "MATCH (n:Point {id:$id})-[r]-(op:Point {is_operator:true})-[r2]-(m:Point) "
111
+ "WHERE m.id <> $id RETURN DISTINCT m.id",
112
+ params={"id": node_id},
113
+ ).result_set
114
+ return [r[0] for r in rows]
tortoise/projection.py ADDED
@@ -0,0 +1,37 @@
1
+ from __future__ import annotations
2
+
3
+ """DEPRECATED — This flat file is dead code.
4
+
5
+ `tortoise.projection` resolves to the canonical package at
6
+ `tortoise/projection/__init__.py`. This shim delegates to the
7
+ package via importlib to avoid circular imports (this file IS
8
+ `tortoise.projection` during its own loading, so a direct
9
+ `from tortoise.projection import *` would be circular).
10
+
11
+ All implementations, entity handlers, and edge handlers live in
12
+ the package submodules (entities.py, edges.py, grounding.py,
13
+ propagation.py) — never modify this shim.
14
+ """
15
+ import sys as _sys
16
+ import importlib as _importlib
17
+
18
+ # Remove this shim from sys.modules temporarily so importlib finds
19
+ # the canonical package at tortoise/projection/__init__.py
20
+ _shim_module = _sys.modules.pop('tortoise.projection', None)
21
+
22
+ # Load the canonical package
23
+ _pkg = _importlib.import_module('tortoise.projection')
24
+
25
+ # Re-export canonical public symbols
26
+ FalkorProjection = _pkg.FalkorProjection
27
+ InMemoryProjection = _pkg.InMemoryProjection
28
+ Projection = _pkg.Projection
29
+ fold = _pkg.fold
30
+ split = _pkg.split
31
+ _apply_one = _pkg._apply_one
32
+ _now_iso = _pkg._now_iso
33
+ _norm = _pkg._norm
34
+
35
+ # Restore this shim as tortoise.projection so downstream relative
36
+ # imports (from .projection import ...) resolve correctly
37
+ _sys.modules['tortoise.projection'] = _sys.modules[__name__]
tortoise/quadrature.py ADDED
@@ -0,0 +1,90 @@
1
+ """Gauss-Jacobi quadrature on [0,1] for Beta-weighted integrals.
2
+
3
+ Used by TortoiseEP for numerical moment projection of NAND/IMPL factors.
4
+
5
+ scipy.special.roots_jacobi uses weight (1-x)^a * (1+x)^b on [-1,1].
6
+ For Beta(α,β) weight x^(α-1)*(1-x)^(β-1) on [0,1]:
7
+ Transform: x_01 = (x_jac + 1) / 2, w_01 = w_jac / 2
8
+ Mapping: scipy a = β-1, scipy b = α-1 (swapped convention)
9
+ """
10
+ import numpy as np
11
+ from scipy.special import roots_jacobi
12
+
13
+
14
+ def gauss_jacobi_01(n: int, alpha: float, beta: float):
15
+ """Gauss-Jacobi nodes and weights on [0,1] for weight x^(alpha-1)*(1-x)^(beta-1)."""
16
+ x_jac, w_jac = roots_jacobi(n, beta - 1, alpha - 1)
17
+ return (x_jac + 1) / 2, w_jac / 2
18
+
19
+
20
+ def tilted_moments(alpha_a, beta_a, alpha_b, beta_b, w, phi_fn, n_quad=8):
21
+ """Compute E[c_a], E[c_a²], E[c_b], E[c_b²] under tilted distribution.
22
+
23
+ P̃ ∝ Beta(c_a;α_a,β_a) × Beta(c_b;α_b,β_b) × φ(c_a, c_b)
24
+
25
+ Returns ((m1_a, m2_a), (m1_b, m2_b)) where m1=E[c], m2=E[c²].
26
+ """
27
+ x_a, w_a = gauss_jacobi_01(n_quad, alpha_a, beta_a)
28
+ x_b, w_b = gauss_jacobi_01(n_quad, alpha_b, beta_b)
29
+
30
+ # Vectorized: compute phi matrix via numpy broadcasting (n_quad × n_quad)
31
+ ca_grid = x_a.reshape(-1, 1) # (n_quad, 1)
32
+ cb_grid = x_b.reshape(1, -1) # (1, n_quad)
33
+ weight_grid = w_a.reshape(-1, 1) * w_b.reshape(1, -1)
34
+ phi_grid = phi_fn(ca_grid, cb_grid, w)
35
+ weighted = weight_grid * phi_grid
36
+ Z = np.sum(weighted)
37
+
38
+ if Z < 1e-30:
39
+ tw_a = np.sum(w_a)
40
+ tw_b = np.sum(w_b)
41
+ m1_a = np.sum(w_a * x_a) / tw_a
42
+ m2_a = np.sum(w_a * x_a * x_a) / tw_a
43
+ m1_b = np.sum(w_b * x_b) / tw_b
44
+ m2_b = np.sum(w_b * x_b * x_b) / tw_b
45
+ return (m1_a, m2_a), (m1_b, m2_b)
46
+
47
+ # Vectorized moments: sum over both dimensions
48
+ m1_a = np.sum(weighted * ca_grid) / Z
49
+ m2_a = np.sum(weighted * ca_grid * ca_grid) / Z
50
+ m1_b = np.sum(weighted * cb_grid) / Z
51
+ m2_b = np.sum(weighted * cb_grid * cb_grid) / Z
52
+ return (m1_a, m2_a), (m1_b, m2_b)
53
+
54
+
55
+ def moments_to_beta(m1, m2):
56
+ """Convert E[c] and E[c²] to Beta(α, β) parameters."""
57
+ var = max(m2 - m1 * m1, 1e-12)
58
+ if var >= m1 * (1 - m1) * 0.999:
59
+ return (1.0, 1.0)
60
+ total = m1 * (1 - m1) / var - 1
61
+ if total <= 0:
62
+ return (1.0, 1.0)
63
+ alpha = max(total * m1, 0.01)
64
+ beta = max(total * (1 - m1), 0.01)
65
+ return (alpha, beta)
66
+
67
+
68
+ def phi_nand(ca, cb, w=8.0):
69
+ """Symmetric NAND: equal-quality contradiction returns to ~50%.
70
+
71
+ Uses averaged mirrored product coupling:
72
+ exp(-w * (ca*(1-cb) + cb*(1-ca)) / 2)
73
+
74
+ Symmetric in (ca, cb) — result is independent of argument order.
75
+ When both T0(0.91): phi ≈ 0.637 — moderate dampening per message.
76
+ When both baseline(0.5): phi ≈ 0.064 — strong contradiction push.
77
+ Previously exp(-w * ca * (1-cb)) was asymmetric, causing 3-8× difference
78
+ depending on which claim was assigned to argument position ca.
79
+ """
80
+ return np.exp(-w * (ca * (1 - cb) + cb * (1 - ca)) / 2)
81
+
82
+
83
+ def phi_impl(ca, cb, w=8.0):
84
+ """IMPL coupling factor: promotes agreement between connected claims.
85
+
86
+ Product coupling exp(w * ca * cb) transmits confidence from strong to weak.
87
+ At w=5.5: a T0 source (91%) pushes a baseline target to 72-78%.
88
+ Previously w=3.0 was too weak, requiring a cavity boost hack.
89
+ """
90
+ return np.exp(w * ca * cb)
@@ -0,0 +1,194 @@
1
+ """Query suggestions for silent-empty query results (#49 task 1.4).
2
+
3
+ Provides Levenshtein-based "did you mean?" suggestions for misspelled
4
+ kind/namespace names, and a distinct hint when the kind is valid but
5
+ simply has 0 points in the graph.
6
+
7
+ No external dependencies — Levenshtein is implemented inline.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+
13
+ _logger = logging.getLogger(__name__)
14
+
15
+ # Max edit distance for typo suggestions (<= 2 = common typos)
16
+ _MAX_DISTANCE = 2
17
+
18
+
19
+ # ── Levenshtein (edit distance) ────────────────────────────────────────
20
+
21
+ def levenshtein(s: str, t: str) -> int:
22
+ """Compute Levenshtein edit distance between two strings.
23
+
24
+ Standard dynamic-programming implementation — insert, delete, substitute.
25
+ """
26
+ if len(s) < len(t):
27
+ s, t = t, s
28
+ # s is the longer string
29
+ m, n = len(s), len(t)
30
+ # Two-row DP — O(m*n) time, O(n) space
31
+ prev = list(range(n + 1))
32
+ curr = [0] * (n + 1)
33
+ for i in range(1, m + 1):
34
+ curr[0] = i
35
+ for j in range(1, n + 1):
36
+ cost = 0 if s[i - 1] == t[j - 1] else 1
37
+ curr[j] = min(
38
+ prev[j] + 1, # delete
39
+ curr[j - 1] + 1, # insert
40
+ prev[j - 1] + cost # substitute
41
+ )
42
+ prev, curr = curr, prev
43
+ return prev[n]
44
+
45
+
46
+ # ── Suggestion engine ──────────────────────────────────────────────────
47
+
48
+ def suggest_kind(query_kind: str, known_kinds: list[str],
49
+ max_suggestions: int = 3) -> list[str]:
50
+ """Return closest known kinds by Levenshtein distance to a misspelled kind.
51
+
52
+ Only suggestions within edit distance <= 2 (typographical).
53
+ Sorted by distance, then alphabetically.
54
+
55
+ Args:
56
+ query_kind: The kind the user typed (potentially misspelled).
57
+ known_kinds: All known kind names (from pack registry).
58
+ max_suggestions: Maximum number of suggestions to return.
59
+
60
+ Returns:
61
+ List of matching kind names, or empty list if no close match.
62
+ """
63
+ # Handle namespace-prefixed kinds (e.g., "product-strategy:featuer")
64
+ if ":" in query_kind:
65
+ ns, local = query_kind.split(":", 1)
66
+ # Filter known kinds to same namespace
67
+ ns_prefix = f"{ns}:"
68
+ candidates = [k for k in known_kinds if k.startswith(ns_prefix)]
69
+ # Compare against the local part
70
+ scored = []
71
+ for candidate in candidates:
72
+ _cns, clocal = candidate.split(":", 1)
73
+ dist = levenshtein(local, clocal)
74
+ if dist <= _MAX_DISTANCE:
75
+ scored.append((dist, candidate))
76
+ scored.sort(key=lambda x: (x[0], x[1]))
77
+ return [s[1] for s in scored[:max_suggestions]]
78
+
79
+ # Bare kind — compare against both local parts and full prefixed forms
80
+ scored = []
81
+ for candidate in known_kinds:
82
+ if ":" in candidate:
83
+ _ns, clocal = candidate.split(":", 1)
84
+ dist_local = levenshtein(query_kind, clocal)
85
+ dist_full = levenshtein(query_kind, candidate)
86
+ dist = min(dist_local, dist_full)
87
+ else:
88
+ dist = levenshtein(query_kind, candidate)
89
+ if dist <= _MAX_DISTANCE:
90
+ scored.append((dist, candidate))
91
+ scored.sort(key=lambda x: (x[0], x[1]))
92
+ return [s[1] for s in scored[:max_suggestions]]
93
+
94
+
95
+ def _collect_known_kinds() -> list[str]:
96
+ """Collect all pointKinds + objectKinds from canonical vocabulary + packs.
97
+
98
+ Returns both prefixed (namespace:kind) and bare (kind) forms so that
99
+ suggest_kind can match against either representation.
100
+ """
101
+ try:
102
+ from .pack_registry import (
103
+ PackRegistry,
104
+ CANONICAL_POINT_KINDS,
105
+ CANONICAL_OBJECT_KINDS,
106
+ )
107
+ from pathlib import Path as _Path
108
+ packs_dir = _Path(__file__).resolve().parent.parent / "packs"
109
+ registry = PackRegistry(packs_dir)
110
+ registry.load_all()
111
+ kinds: list[str] = []
112
+ # Canonical base vocabulary (what CAN exist by default)
113
+ kinds.extend(sorted(CANONICAL_POINT_KINDS))
114
+ kinds.extend(sorted(CANONICAL_OBJECT_KINDS))
115
+ # Pack kinds
116
+ all_kinds = registry.list_all_kinds()
117
+ for kind_field in ("pointKinds", "objectKinds"):
118
+ for k in all_kinds.get(kind_field, []):
119
+ kinds.append(k)
120
+ if ":" in k:
121
+ # Also add bare form for matching
122
+ kinds.append(k.split(":", 1)[1])
123
+ # Deduplicate
124
+ return sorted(set(kinds))
125
+ except Exception:
126
+ _logger.warning("Failed to load pack registry for query suggestions", exc_info=True)
127
+ return []
128
+
129
+
130
+ def compute_suggestion(kind: str) -> str | None:
131
+ """Compute a suggestion/hint for a kind that returned 0 results.
132
+
133
+ Two cases:
134
+ 1. Kind IS a valid registered kind → hint that it exists but has 0 points
135
+ 2. Kind is NOT valid → "did you mean" Levenshtein suggestions
136
+
137
+ Returns a suggestion string, or None if no suggestion can be made.
138
+ """
139
+ known = _collect_known_kinds()
140
+ if not known:
141
+ return None
142
+
143
+ # Check if the kind is a valid registered kind
144
+ # Match against both full prefixed forms and bare forms
145
+ is_valid = kind in known
146
+ if not is_valid and ":" not in kind:
147
+ # bare kind — check if any prefixed form matches
148
+ for k in known:
149
+ if ":" in k and k.split(":", 1)[1] == kind:
150
+ is_valid = True
151
+ break
152
+
153
+ if is_valid:
154
+ # Valid kind, but 0 points — give a hint (not did-you-mean)
155
+ return (
156
+ f"kind '{kind}' is valid but has 0 points in the graph. "
157
+ "Try list_pointkinds() to see kinds present in the graph, "
158
+ "or list_sources() to browse by provenance."
159
+ )
160
+
161
+ # Not valid — try Levenshtein suggestions
162
+ suggestions = suggest_kind(kind, known)
163
+ if suggestions:
164
+ quoted = ", ".join(f"'{s}'" for s in suggestions)
165
+ return f"kind '{kind}' not found. Did you mean: {quoted}?"
166
+
167
+ return None
168
+
169
+
170
+ # ── SDK wrapper ────────────────────────────────────────────────────────
171
+
172
+ def query_with_suggestions(query_fn, kind: str | None = None,
173
+ **filters) -> dict:
174
+ """Call query_fn (e.g., sdk.query) and attach suggestion for silent-empty results.
175
+
176
+ Returns:
177
+ dict with keys:
178
+ - results: the query results list
179
+ - suggestion: (only present when results empty and kind provided)
180
+ a hint or "did you mean" string
181
+ """
182
+ results = query_fn(kind, **filters)
183
+
184
+ if results:
185
+ return {"results": results}
186
+
187
+ if not kind:
188
+ return {"results": results}
189
+
190
+ suggestion = compute_suggestion(kind)
191
+ if suggestion:
192
+ _logger.warning("Query suggestion: %s", suggestion)
193
+ return {"results": results, "suggestion": suggestion}
194
+ return {"results": results}
tortoise/quota.py ADDED
@@ -0,0 +1,163 @@
1
+ """Per-team quota enforcement shared by REST and MCP (#329).
2
+
3
+ Design: limits are resolved ONCE by the authenticated caller
4
+ (``hosted_api.get_current_team`` / MCP ``TeamResolutionMiddleware``) via
5
+ ``resolve_team_limits`` and passed to ``enforce_team_limit`` — never re-fetched
6
+ per write. Counting is fail-closed: any counting exception raises
7
+ ``QuotaCheckError`` (server error), never a silent pass.
8
+
9
+ Import topology: stdlib-only at module level; ``tortoise.sdk`` imported
10
+ function-level inside the helpers to avoid any cycle (hosted_api → mcp_server
11
+ → mcp_auth → sdk is the canonical direction; quota is a leaf consumer).
12
+
13
+ No team context (stdio/operator) → ``enforce_team_limit(None, ...)`` returns
14
+ cleanly (skip) — mirrors REST ``_check_team_limit``'s ``if not team_id: return``.
15
+ Batch caps are unconditional in both modes.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import os
20
+ import tempfile
21
+
22
+
23
+ def _make_sdk(*, namespace: str | None = None):
24
+ """Build a TortoiseSDK with hosted_api._make_sdk's precedence (inline copy —
25
+ quota is a leaf consumer and must not import hosted_api).
26
+
27
+ URI mode (docker:// / redis:// / rediss://) when TORTOISE_DB_URI is set;
28
+ else embedded via TORTOISE_DB_PATH (default /data/tortoise.db) with a
29
+ tempfile fallback when the volume is unwritable (test env).
30
+ """
31
+ from tortoise.sdk import TortoiseSDK # function-level: avoid cycles
32
+ if os.environ.get("TORTOISE_DB_URI"):
33
+ return TortoiseSDK(namespace=namespace)
34
+ db_path = os.environ.get("TORTOISE_DB_PATH", "/data/tortoise.db")
35
+ try:
36
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
37
+ except OSError:
38
+ db_path = os.path.join(tempfile.gettempdir(), "tortoise.db")
39
+ return TortoiseSDK(db_path=db_path, namespace=namespace)
40
+
41
+
42
+ # ── Batch-cap constants (unconditional — both modes) ───────────────────────
43
+ MAX_CHECKPOINT_ITEMS = 500
44
+ MAX_FILE_DECISION_OPTIONS = 50
45
+ MAX_FILE_DECISION_EVIDENCE = 100
46
+ MAX_TAGS_PER_POINT = 50
47
+ MAX_OPERATOR_TARGETS = 500
48
+ MAX_SESSION_TURNS = 500
49
+ MAX_EXTRACTIONS_PER_TURN = 200
50
+ MAX_ANALYZE_LLM_PER_MIN = 60
51
+ MAX_DREAM_FULL_PER_HOUR = 6
52
+
53
+ # ── Default limits (match REST today: team.get("max_points") or 1000) ──────
54
+ DEFAULT_MAX_POINTS = 1000
55
+ DEFAULT_MAX_API_KEYS = 20
56
+ DEFAULT_MAX_SESSIONS = 1000
57
+
58
+ _RESOURCE_LIMIT_KEYS = {
59
+ "points": "max_points",
60
+ "api_keys": "max_api_keys",
61
+ "sessions": "max_sessions",
62
+ }
63
+
64
+
65
+ class QuotaExceededError(Exception):
66
+ """Team is at/over its resource limit — the write must be rejected (402)."""
67
+
68
+
69
+ class QuotaCheckError(Exception):
70
+ """Quota counting/config failed — fail closed (500/503), never pass."""
71
+
72
+
73
+ def resolve_team_limits(team_id: str) -> dict:
74
+ """Resolve a team's limits from the registry Team node.
75
+
76
+ Missing Team node → QuotaCheckError (fail-closed; the auth layer should
77
+ guarantee key→team mapping). Missing attributes → defaults
78
+ (1000/20/1000 — matching today's effective behavior).
79
+ """
80
+ if not team_id:
81
+ raise QuotaCheckError("resolve_team_limits requires a team_id")
82
+ reg = _make_sdk(namespace="registry")
83
+ rows = reg._get_registry().query(
84
+ "MATCH (t:Team {id:$id}) "
85
+ "RETURN t.tier, t.max_points, t.max_api_keys, t.max_sessions",
86
+ params={"id": team_id},
87
+ ).result_set
88
+ if not rows:
89
+ raise QuotaCheckError(f"Team {team_id!r} not found in registry")
90
+ tier, mp, mak, ms = rows[0]
91
+ return {
92
+ "team_id": team_id,
93
+ "tier": tier or "free",
94
+ "max_points": int(mp) if mp is not None else DEFAULT_MAX_POINTS,
95
+ "max_api_keys": int(mak) if mak is not None else DEFAULT_MAX_API_KEYS,
96
+ "max_sessions": int(ms) if ms is not None else DEFAULT_MAX_SESSIONS,
97
+ }
98
+
99
+
100
+ def count_team_usage(team_id: str, resource: str, sdk=None) -> int:
101
+ """Count current usage for a resource. Raises QuotaCheckError on failure.
102
+
103
+ Public so callers needing the raw count (e.g. extraction-aware estimates)
104
+ can use it without duplicating the fail-closed handling.
105
+ """
106
+ return _count_resource(team_id, resource, sdk=sdk)
107
+
108
+
109
+ def _count_resource(team_id: str, resource: str, sdk=None) -> int:
110
+ """Count current usage for a resource. Raises QuotaCheckError on failure."""
111
+ try:
112
+ if resource == "api_keys":
113
+ reg = (sdk if sdk is not None and getattr(sdk, "_namespace", None) == "registry"
114
+ else _make_sdk(namespace="registry"))
115
+ rows = reg._get_registry().query(
116
+ "MATCH (k:APIKey {team_id: $tid}) WHERE k.revoked_at IS NULL RETURN count(k)",
117
+ params={"tid": team_id},
118
+ ).result_set
119
+ return int(rows[0][0])
120
+ else:
121
+ if sdk is None:
122
+ sdk = _make_sdk(namespace=team_id)
123
+ rows = sdk._get_proj().g.query(
124
+ "MATCH (n) RETURN count(n)",
125
+ ).result_set
126
+ return int(rows[0][0])
127
+ except QuotaCheckError:
128
+ raise
129
+ except Exception as e:
130
+ from .security import redact_error
131
+ raise QuotaCheckError(f"quota count failed for {resource}: {redact_error(e)}") from e
132
+
133
+
134
+ def enforce_team_limit(limits: dict | None, resource: str, sdk=None) -> None:
135
+ """Reject a write when the team is at/over its resource limit.
136
+
137
+ Args:
138
+ limits: resolved team limits dict (from resolve_team_limits or the
139
+ authenticated caller). None → skip (stdio/operator, no team).
140
+ resource: "points" | "api_keys" | "sessions".
141
+ sdk: pre-built team SDK (REST callers already hold one) — optional.
142
+
143
+ Raises:
144
+ QuotaExceededError: team at/over limit (402-equivalent).
145
+ QuotaCheckError: counting failed (fail-closed).
146
+ """
147
+ if limits is None:
148
+ return # stdio/operator — no team context
149
+ team_id = limits.get("team_id")
150
+ if not team_id:
151
+ return
152
+ limit_key = _RESOURCE_LIMIT_KEYS.get(resource)
153
+ if limit_key is None:
154
+ raise QuotaCheckError(f"unknown quota resource: {resource!r}")
155
+ limit = limits.get(limit_key)
156
+ if limit is None:
157
+ limit = DEFAULT_MAX_POINTS if resource == "points" else (
158
+ DEFAULT_MAX_API_KEYS if resource == "api_keys" else DEFAULT_MAX_SESSIONS)
159
+ count = _count_resource(team_id, resource, sdk=sdk)
160
+ if count >= limit:
161
+ raise QuotaExceededError(
162
+ f"Team {resource} limit reached ({limit}). Upgrade your plan to increase it."
163
+ )