tortoise-graph 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
tortoise/hosted_api.py ADDED
@@ -0,0 +1,1982 @@
1
+ """FastAPI app for Tortoise Hosted Platform.
2
+
3
+ Provides the internal /provision endpoint called by the Supabase
4
+ tenant-provision Edge Function, and will be extended with the full
5
+ multi-tenant REST API (issue #7717).
6
+
7
+ See: docs/epics/2026-08-03-tortoise-hosted-platform/04-plan.md §5, §6.1
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json as _json
13
+ import logging
14
+ import os
15
+ import time
16
+ from collections import defaultdict
17
+ from datetime import datetime, timezone
18
+
19
+ from fastapi import Depends, FastAPI, HTTPException, Query, Request, Response
20
+ from fastapi.responses import RedirectResponse
21
+ from fastapi.middleware.cors import CORSMiddleware
22
+ from starlette.middleware.base import BaseHTTPMiddleware
23
+ from contextlib import asynccontextmanager
24
+
25
+ from tortoise.audit_events import AuditLogger
26
+ from tortoise.auth import hash_api_key
27
+ import hmac
28
+
29
+ from tortoise.sdk import TortoiseSDK, _content_hash
30
+ from tortoise.mcp_server import create_http_app
31
+
32
+ _logger = logging.getLogger(__name__)
33
+
34
+
35
+ def _make_sdk(*, namespace: str | None = None) -> TortoiseSDK:
36
+ """Build an SDK backed by TORTOISE_DB_URI, or embedded mode when unset.
37
+
38
+ Embedded fallback: when no URI is configured (fly.toml default), the SDK
39
+ previously received no path and FalkorProjection raised
40
+ "Either path or host must be provided" — every /internal/provision call
41
+ failed with 500. Using an on-disk redislite DB keeps onboarding functional
42
+ until a production FalkorDB instance is provisioned (#7722).
43
+ """
44
+ if os.environ.get("TORTOISE_DB_URI"):
45
+ return TortoiseSDK(namespace=namespace)
46
+ db_path = os.environ.get("TORTOISE_DB_PATH", "/data/tortoise.db")
47
+ try:
48
+ os.makedirs(os.path.dirname(db_path), exist_ok=True)
49
+ except OSError:
50
+ # /data volume not writable (test env, or volume not mounted yet) —
51
+ # fall back to a temp file so provisioning still works.
52
+ import tempfile
53
+ db_path = os.path.join(tempfile.gettempdir(), "tortoise.db")
54
+ return TortoiseSDK(db_path=db_path, namespace=namespace)
55
+
56
+
57
+ # ── MCP Streamable HTTP sub-app (#236) ────────────────────────────
58
+ # Built BEFORE _lifespan references it (no unbound reference). Mounted at /mcp
59
+ # — the MCP app carries its own auth/rate-limit/security middleware stack;
60
+ # FastAPI parent middleware does NOT propagate to mounted sub-apps.
61
+ _MCP_ALLOWED_ORIGINS = [
62
+ "https://premiselabs.co",
63
+ "https://app.premiselabs.co",
64
+ "https://api.premiselabs.co",
65
+ "https://tortoise-y4mjjq.fly.dev",
66
+ ]
67
+
68
+ _MCP_ALLOWED_HOSTS = [o.split("//")[1].split("/")[0] for o in _MCP_ALLOWED_ORIGINS if "//" in o]
69
+
70
+ mcp_http_app = create_http_app(
71
+ allowed_origins=_MCP_ALLOWED_ORIGINS,
72
+ allowed_hosts=_MCP_ALLOWED_HOSTS,
73
+ rate_limit=100,
74
+ )
75
+
76
+
77
+ @asynccontextmanager
78
+ async def _lifespan(app):
79
+ """Compose the FastMCP sub-app's lifespan (session manager init) into
80
+ the parent FastAPI lifespan. Starlette's Mount does NOT run the mounted
81
+ app's lifespan automatically — explicit composition required.
82
+
83
+ mcp_http_app.lifespan(mcp_http_app) is the Starlette Lifespan protocol
84
+ (async context manager) that initializes the StreamableHTTPSessionManager.
85
+
86
+ Also spawns a NON-BLOCKING embedding model pre-warm in a daemon thread
87
+ (#545): uvicorn must bind 0.0.0.0:8000 immediately so /health passes on
88
+ cold start. The previous entrypoint fail-fast pre-warm crashed deploys
89
+ when the 30s load timeout was exceeded on a cold 2GB VM. Embeddings are
90
+ OPTIONAL — if the pre-warm misses its window, EmbeddingModel.get()
91
+ retries on the next call and search falls back to FTS+structural RRF.
92
+ """
93
+ async with mcp_http_app.lifespan(mcp_http_app):
94
+ try:
95
+ import threading
96
+
97
+ def _prewarm_embeddings() -> None:
98
+ try:
99
+ from tortoise.embeddings import EmbeddingModel
100
+ # Longer window than request paths (30s): cold-start torch
101
+ # import on a 2-core/2GB VM can exceed 30s (#545). The
102
+ # thread is daemon + background, so it never blocks bind.
103
+ model = EmbeddingModel.get(load_timeout=300.0)
104
+ _logger.info(
105
+ "embeddings: background pre-warm %s",
106
+ "ready" if model is not None else "deferred (retries on next call)",
107
+ )
108
+ except Exception as exc: # noqa: BLE001 — never crash the app
109
+ _logger.warning("embeddings: background pre-warm failed: %s", exc)
110
+
111
+ threading.Thread(target=_prewarm_embeddings, name="embedding-prewarm", daemon=True).start()
112
+ except Exception as exc: # noqa: BLE001
113
+ _logger.warning("embeddings: could not start background pre-warm: %s", exc)
114
+ yield
115
+
116
+
117
+ app = FastAPI(title="Tortoise Hosted API", version="0.1.0", lifespan=_lifespan)
118
+
119
+ app.add_middleware(
120
+ CORSMiddleware,
121
+ allow_origins=["https://premiselabs.co", "https://app.premiselabs.co", "https://api.premiselabs.co", "https://tortoise-y4mjjq.fly.dev"],
122
+ allow_methods=["*"],
123
+ allow_headers=["*"],
124
+ )
125
+
126
+ # ── Dreaming queue (#85) ────────────────────────────────────────────────
127
+ # Per-tenant async queue: writes enqueue the affected roots; a cooperative
128
+ # per-tenant drain task runs incremental EP dreaming. Serialized per tenant
129
+ # (never two concurrent dreams on one tenant graph). Debounced 100ms so
130
+ # bursty writes batch into one dream. Server-mode FalkorDB handles
131
+ # concurrency natively — this is a cooperative asyncio task, not a thread
132
+ # (no SQLite/redislite single-writer hazard, #6761/#176).
133
+ _DREAM_QUEUES: dict[str, asyncio.Queue] = {}
134
+ # #329: per-team hourly budget for /v1/dream?full=true (CPU DoS bound)
135
+ _DREAM_FULL_BUCKETS: dict[str, list[float]] = {}
136
+ _DREAM_TASKS: dict[str, asyncio.Task] = {}
137
+ _DREAM_DEBOUNCE_S = 0.1
138
+ _DREAM_BATCH_MAX = 200
139
+ # Evict idle tenant queues after this many seconds (security P2, #85) so
140
+ # per-tenant queue/task dicts don't grow unboundedly across many tenants.
141
+ _DREAM_QUEUE_TTL_S = 600
142
+
143
+
144
+ def _enqueue_dream(team_id: str, dirty_roots: list[str]) -> None:
145
+ """Enqueue affected roots for a tenant's next dream cycle."""
146
+ if not dirty_roots:
147
+ return
148
+ q = _DREAM_QUEUES.setdefault(team_id, asyncio.Queue())
149
+ for root in dirty_roots[: _DREAM_BATCH_MAX]:
150
+ q.put_nowait(root)
151
+ if team_id not in _DREAM_TASKS or _DREAM_TASKS[team_id].done():
152
+ _DREAM_TASKS[team_id] = asyncio.create_task(_dream_worker(team_id))
153
+
154
+
155
+ async def _dream_worker(team_id: str) -> None:
156
+ """Drain one tenant's queue with debounce, then run incremental dream."""
157
+ q = _DREAM_QUEUES.get(team_id)
158
+ if q is None:
159
+ return
160
+ try:
161
+ # Debounce: collect roots that arrive within the window.
162
+ await asyncio.sleep(_DREAM_DEBOUNCE_S)
163
+ roots: list[str] = []
164
+ while not q.empty() and len(roots) < _DREAM_BATCH_MAX:
165
+ roots.append(q.get_nowait())
166
+ if not roots:
167
+ return
168
+ sdk = _make_sdk(namespace=team_id)
169
+ try:
170
+ # Batch mark once (P3, #85) — one reverse-BFS pair, not N.
171
+ sdk._mark_dirty(roots)
172
+ sdk.dream(dirty_only=True)
173
+ finally:
174
+ sdk.close()
175
+ except Exception:
176
+ import logging
177
+ logging.getLogger("tortoise.api").exception(
178
+ "dream worker failed for tenant %s", team_id
179
+ )
180
+ finally:
181
+ # Reschedule if more roots arrived during the drain.
182
+ if not q.empty():
183
+ _DREAM_TASKS[team_id] = asyncio.create_task(_dream_worker(team_id))
184
+ elif team_id in _DREAM_QUEUES and team_id in _DREAM_TASKS:
185
+ # Idle: evict the queue (TTL guard) unless a new write re-adds it.
186
+ _DREAM_QUEUES.pop(team_id, None)
187
+ _DREAM_TASKS.pop(team_id, None)
188
+
189
+
190
+ # ── Rate Limiter ──────────────────────────────────────────────────
191
+
192
+ class RateLimitMiddleware(BaseHTTPMiddleware):
193
+ """In-memory token bucket rate limiter. 100 Points/min per API key."""
194
+
195
+ SKIP = {"/health", "/health/ready", "/docs", "/openapi.json", "/v1/register"}
196
+
197
+ def __init__(self, app, max_per_minute=100):
198
+ super().__init__(app)
199
+ self.max_per_minute = max_per_minute
200
+ self._buckets: dict[str, list[float]] = defaultdict(list)
201
+ self._last_cleanup = time.time()
202
+ self._lock = asyncio.Lock()
203
+ # RATE_LIMIT_DISABLED=1 disables throttling (test env) — the test
204
+ # suite creates >100 points per run against a shared IP bucket,
205
+ # tripping 429 in full-suite runs. Production keeps the limit.
206
+ self._disabled = os.environ.get("RATE_LIMIT_DISABLED") == "1"
207
+
208
+ async def dispatch(self, request: Request, call_next):
209
+ if self._disabled:
210
+ return await call_next(request)
211
+ if request.url.path in self.SKIP or request.url.path.startswith("/internal"):
212
+ return await call_next(request)
213
+
214
+ auth = request.headers.get("Authorization", "")
215
+ if not auth.startswith("Bearer ") or not auth[7:].startswith("tt_"):
216
+ # IP-based fallback for unauthenticated requests
217
+ if request.client and request.client.host:
218
+ key_id = f"ip:{request.client.host}"
219
+ else:
220
+ return await call_next(request)
221
+ else:
222
+ # Use API key as bucket key (per-key limits, avoids hashing in hot path)
223
+ key_id = auth[7:]
224
+ now = time.time()
225
+
226
+ async with self._lock:
227
+ # Periodic cleanup: prune empty buckets and buckets older than 60s
228
+ if now - self._last_cleanup > 60:
229
+ stale = []
230
+ for k, v in list(self._buckets.items()):
231
+ v[:] = [t for t in v if now - t < 60]
232
+ if not v:
233
+ stale.append(k)
234
+ for k in stale:
235
+ del self._buckets[k]
236
+ self._last_cleanup = now
237
+
238
+ bucket = self._buckets[key_id]
239
+ bucket[:] = [t for t in bucket if now - t < 60]
240
+
241
+ if len(bucket) >= self.max_per_minute:
242
+ raise HTTPException(
243
+ status_code=429,
244
+ detail="Rate limit exceeded. 100 points/minute per API key.",
245
+ headers={"Retry-After": "60"},
246
+ )
247
+
248
+ bucket.append(now)
249
+ return await call_next(request)
250
+
251
+
252
+ app.add_middleware(RateLimitMiddleware, max_per_minute=100)
253
+
254
+
255
+ class HSTSMiddleware(BaseHTTPMiddleware):
256
+ """Add Strict-Transport-Security header to every response."""
257
+
258
+ async def dispatch(self, request: Request, call_next):
259
+ response = await call_next(request)
260
+ response.headers["Strict-Transport-Security"] = (
261
+ "max-age=31536000; includeSubDomains"
262
+ )
263
+ return response
264
+
265
+ app.add_middleware(HSTSMiddleware)
266
+
267
+
268
+ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
269
+ """Add security headers to every response."""
270
+
271
+ async def dispatch(self, request: Request, call_next):
272
+ response = await call_next(request)
273
+ response.headers["X-Content-Type-Options"] = "nosniff"
274
+ response.headers["X-Frame-Options"] = "DENY"
275
+ response.headers["X-XSS-Protection"] = "1; mode=block"
276
+ return response
277
+
278
+
279
+ app.add_middleware(SecurityHeadersMiddleware)
280
+
281
+ # Internal auth key for Edge Function → API communication
282
+ _INTERNAL_KEY = os.environ.get("FASTAPI_INTERNAL_KEY", "")
283
+
284
+
285
+ # ── Audit Event Logger ───────────────────────────────────────────
286
+
287
+ _audit_logger = AuditLogger(dsn=os.environ.get("TORTOISE_AUDIT_DSN"))
288
+
289
+
290
+ async def _async_audit(
291
+ request: Request,
292
+ team_id: str,
293
+ operation: str,
294
+ *,
295
+ resource_type: str | None = None,
296
+ resource_id: str | None = None,
297
+ ) -> None:
298
+ """Async-safe audit event writer. Offloads sync psycopg2 to thread pool."""
299
+ ip = request.client.host if request.client else None
300
+ ua = request.headers.get("user-agent")
301
+ await asyncio.to_thread(
302
+ _audit_logger.append,
303
+ team_id=team_id,
304
+ actor_user_id=None,
305
+ operation=operation,
306
+ resource_type=resource_type,
307
+ resource_id=resource_id,
308
+ ip_address=ip,
309
+ user_agent=ua,
310
+ )
311
+
312
+
313
+ def _check_internal(request: Request) -> None:
314
+ """Verify internal auth — only Edge Functions call this."""
315
+ if not _INTERNAL_KEY:
316
+ raise HTTPException(status_code=503, detail="Internal API not configured")
317
+ auth = request.headers.get("authorization", "")
318
+ if not auth.startswith("Bearer ") or not hmac.compare_digest(auth[7:], _INTERNAL_KEY):
319
+ raise HTTPException(status_code=401, detail="Unauthorized")
320
+
321
+
322
+ @app.post("/internal/provision")
323
+ async def provision_tenant(request: Request):
324
+ """Provision a new team: create Team node + FalkorDB namespace + store API key.
325
+
326
+ Called by the tenant-provision Supabase Edge Function on user signup.
327
+ """
328
+ _check_internal(request)
329
+
330
+ body = await request.json()
331
+ team_id = body.get("team_id")
332
+ team_name = body.get("team_name")
333
+ api_key_hash = body.get("api_key_hash")
334
+ created_by = body.get("created_by")
335
+
336
+ if not all([team_id, team_name, api_key_hash, created_by]):
337
+ raise HTTPException(status_code=400, detail="Missing required fields")
338
+
339
+ # Validate team_id and team_name against allowed pattern
340
+ import re
341
+ _team_pattern = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9 _-]{0,63}$')
342
+ if not _team_pattern.match(team_id):
343
+ raise HTTPException(status_code=400, detail="Invalid team_id format")
344
+ if not _team_pattern.match(team_name):
345
+ raise HTTPException(status_code=400, detail="Invalid team_name format")
346
+
347
+ sdk = _make_sdk(namespace="registry")
348
+ now = datetime.now(timezone.utc).isoformat()
349
+ graph_name = f"team_{team_id}"
350
+
351
+ try:
352
+ # Create Team node in the control_plane registry graph
353
+ sdk._get_registry().query(
354
+ """
355
+ CREATE (t:Team {
356
+ id: $id, name: $name, tier: 'free',
357
+ created_at: $now, backup_enabled: false,
358
+ max_users: 1, max_teams: 1, max_graphs: 1
359
+ })
360
+ """,
361
+ params={"id": team_id, "name": team_name, "now": now},
362
+ )
363
+
364
+ # Create APIKey node
365
+ api_key_id = _short_id()
366
+ sdk._get_registry().query(
367
+ """
368
+ CREATE (k:APIKey {
369
+ id: $id, team_id: $team_id, key_hash: $hash,
370
+ key_prefix: $prefix, created_by: $created_by,
371
+ created_at: $now
372
+ })
373
+ """,
374
+ params={
375
+ "id": api_key_id,
376
+ "team_id": team_id,
377
+ "hash": api_key_hash,
378
+ "prefix": team_id[:8],
379
+ "created_by": created_by,
380
+ "now": now,
381
+ },
382
+ )
383
+
384
+ # Provision FalkorDB namespace for the team
385
+ team_graph = sdk._get_proj().db.select_graph(graph_name)
386
+ team_graph.query(
387
+ "CREATE (:TeamMeta {name: $name, created: $now})",
388
+ params={"name": team_name, "now": now},
389
+ )
390
+
391
+ # Create Membership (creator is Owner)
392
+ sdk._get_registry().query(
393
+ """
394
+ CREATE (m:Membership {
395
+ id: $id, user_id: $user_id, team_id: $team_id,
396
+ role: 'owner', joined_at: $now
397
+ })
398
+ """,
399
+ params={
400
+ "id": _short_id(),
401
+ "user_id": created_by,
402
+ "team_id": team_id,
403
+ "now": now,
404
+ },
405
+ )
406
+
407
+ # Log audit event
408
+ await _async_audit(
409
+ request, team_id, "tenant_provision",
410
+ resource_type="team", resource_id=team_id,
411
+ )
412
+
413
+ return {"status": "provisioned", "team_id": team_id, "graph_name": graph_name}
414
+ except Exception:
415
+ # Full rollback on any failure (registry graph)
416
+ sdk._get_registry().query("MATCH (t:Team {id: $id}) DETACH DELETE t", params={"id": team_id})
417
+ sdk._get_registry().query(
418
+ "MATCH (k:APIKey {team_id: $id}) DETACH DELETE k", params={"id": team_id}
419
+ )
420
+ sdk._get_registry().query(
421
+ "MATCH (m:Membership {team_id: $id}) DETACH DELETE m", params={"id": team_id}
422
+ )
423
+ try:
424
+ team_graph = sdk._get_proj().db.select_graph(graph_name)
425
+ team_graph.delete()
426
+ except Exception:
427
+ pass
428
+ raise HTTPException(status_code=500, detail="Tenant provisioning failed")
429
+
430
+
431
+ def _short_id() -> str:
432
+ """Generate a short unique identifier (26 hex chars, no dashes)."""
433
+ import uuid
434
+ return uuid.uuid4().hex[:26]
435
+
436
+
437
+ @app.get("/health")
438
+ async def health():
439
+ """Liveness — process up and serving. NEVER gates on the DB.
440
+
441
+ (cold-start fix, #338 follow-up): the previous DB-coupled /health caused
442
+ deploy failures on cold machines — Fly caps the http_check grace period at
443
+ 60s, and a cold FalkorDB Cloud connection exceeds it. Liveness returns
444
+ immediately; DB readiness is `/health/ready`.
445
+ """
446
+ return {"status": "ok"}
447
+
448
+
449
+ @app.get("/health/ready")
450
+ async def health_ready():
451
+ """Readiness — DB connectivity (what /health used to check)."""
452
+ db_ok = False
453
+ try:
454
+ sdk = _make_sdk(namespace="registry")
455
+ sdk._get_proj().g.query("RETURN 1")
456
+ db_ok = True
457
+ except Exception:
458
+ pass
459
+ if not db_ok:
460
+ raise HTTPException(status_code=503, detail="Database unreachable")
461
+ return {"status": "ok", "db": "connected"}
462
+
463
+
464
+ @app.get("/health/security")
465
+ async def health_security():
466
+ """Security posture endpoint — verifies pepper, hashing, and auth config."""
467
+ pepper_set = bool(os.environ.get("TORTOISE_SECRET_PEPPER"))
468
+ internal_key_set = bool(os.environ.get("FASTAPI_INTERNAL_KEY"))
469
+ return {
470
+ "pepper_configured": pepper_set,
471
+ "internal_key_configured": internal_key_set,
472
+ "hashing": "pbkdf2_hmac_sha256",
473
+ "api_auth_enforced": not internal_key_set or bool(os.environ.get("FASTAPI_INTERNAL_KEY")),
474
+ }
475
+
476
+ # ── Phase 1a: Core Endpoints ──────────────────────────────────────
477
+
478
+
479
+ # ── Auth Dependency ────────────────────────────────────────────────
480
+
481
+ SKIP_AUTH = {"/health", "/health/ready", "/docs", "/openapi.json", "/v1/register"}
482
+
483
+
484
+ async def _audit_auth_failure(request: Request, reason: str) -> None:
485
+ """Fire-and-forget audit log for an auth failure (401).
486
+
487
+ Offloaded to a thread to avoid blocking the 401 response.
488
+ """
489
+ ip = request.client.host if request.client else None
490
+ try:
491
+ await asyncio.to_thread(
492
+ _audit_logger.append,
493
+ team_id="",
494
+ actor_user_id=None,
495
+ operation=f"auth_failure:{reason}",
496
+ resource_type="api_key",
497
+ resource_id=None,
498
+ ip_address=ip,
499
+ user_agent=request.headers.get("user-agent"),
500
+ )
501
+ except Exception:
502
+ pass # Audit failure must not affect the auth flow
503
+
504
+
505
+ async def get_current_team(request: Request) -> dict:
506
+ if request.url.path in SKIP_AUTH or request.url.path.startswith("/internal"):
507
+ return {"team_id": None, "tier": "free", "key_id": None}
508
+ auth = request.headers.get("Authorization", "")
509
+ if not auth:
510
+ await _audit_auth_failure(request, "missing_header")
511
+ raise HTTPException(status_code=401, detail="Missing Authorization header")
512
+ if not auth.startswith("Bearer "):
513
+ await _audit_auth_failure(request, "bad_scheme")
514
+ raise HTTPException(status_code=401, detail="Authorization header must use Bearer scheme")
515
+ token = auth[7:]
516
+ if not token.startswith("tt_"):
517
+ await _audit_auth_failure(request, "invalid_format")
518
+ raise HTTPException(status_code=401, detail="Invalid API key format")
519
+ try:
520
+ sdk = _make_sdk(namespace="registry")
521
+ # API keys are stored as "salt:hash" (per-key random salt). hash_api_key()
522
+ # generates a NEW random salt per call, so we CANNOT look up by exact
523
+ # match. Instead fetch all non-revoked keys and verify each against the
524
+ # token using the embedded salt (verify_api_key). This is O(keys) but
525
+ # the registry is small (teams × keys) and auth happens per-request.
526
+ key_result = sdk._get_registry().query(
527
+ "MATCH (k:APIKey) WHERE k.revoked_at IS NULL RETURN k.team_id, k.id, k.key_hash"
528
+ ).result_set
529
+ from tortoise.auth import verify_api_key
530
+ team_id = key_id = None
531
+ for k_team_id, k_id, stored_hash in key_result:
532
+ if verify_api_key(token, stored_hash):
533
+ team_id, key_id = k_team_id, k_id
534
+ break
535
+ if team_id is None:
536
+ await _audit_auth_failure(request, "invalid_key")
537
+ raise HTTPException(status_code=401, detail="Invalid API key")
538
+ # #329: fetch quota limits in the SAME fetch as tier (one round-trip;
539
+ # mirrors quota.resolve_team_limits so REST and MCP see identical limits).
540
+ team = sdk._get_registry().query(
541
+ "MATCH (t:Team {id: $id}) RETURN t.tier, t.max_users, t.max_graphs, "
542
+ "t.max_teams, t.max_points, t.max_api_keys, t.max_sessions",
543
+ params={"id": team_id},
544
+ )
545
+ row = team.result_set[0] if team.result_set else None
546
+ if row:
547
+ tier, mu, mg, mt, mp, mak, ms = row
548
+ else:
549
+ tier, mu, mg, mt, mp, mak, ms = ("free", 1, 1, 1, None, None, None)
550
+ from tortoise.quota import DEFAULT_MAX_API_KEYS, DEFAULT_MAX_POINTS, DEFAULT_MAX_SESSIONS
551
+ request.state.team_id = team_id
552
+ request.state.tier = tier or "free"
553
+ return {"team_id": team_id, "key_id": key_id, "tier": tier or "free",
554
+ "max_users": mu or 1, "max_graphs": mg or 1, "max_teams": mt or 1,
555
+ "max_points": int(mp) if mp is not None else DEFAULT_MAX_POINTS,
556
+ "max_api_keys": int(mak) if mak is not None else DEFAULT_MAX_API_KEYS,
557
+ "max_sessions": int(ms) if ms is not None else DEFAULT_MAX_SESSIONS}
558
+ except HTTPException:
559
+ raise
560
+ except Exception:
561
+ raise HTTPException(status_code=500, detail="Auth error")
562
+
563
+
564
+ def _check_team_limit(team: dict, resource: str) -> None:
565
+ """Enforce per-team limits. Raises 402 (payment required) when at capacity.
566
+
567
+ resource: 'points' | 'api_keys' | 'sessions'
568
+
569
+ #329: delegates to the shared fail-closed quota helper — counting errors
570
+ now surface as 500 (QuotaCheckError) instead of silently passing, and the
571
+ limits dict is the authenticated team dict (resolved once by
572
+ get_current_team), matching MCP semantics.
573
+ """
574
+ team_id = team.get("team_id")
575
+ if not team_id:
576
+ return # internal/no-team context — skip
577
+ from tortoise.quota import (QuotaCheckError, QuotaExceededError,
578
+ enforce_team_limit)
579
+ try:
580
+ enforce_team_limit(team, resource)
581
+ except QuotaExceededError as e:
582
+ raise HTTPException(status_code=402, detail=str(e))
583
+ except QuotaCheckError as e:
584
+ raise HTTPException(status_code=500, detail=f"Quota check failed: {e}")
585
+
586
+
587
+
588
+
589
+ # ── Pydantic Models ───────────────────────────────────────────────
590
+
591
+ from pydantic import BaseModel, Field, field_validator
592
+
593
+
594
+ class CreatePointRequest(BaseModel):
595
+ content: str = Field(..., min_length=1, max_length=10000)
596
+ kind: str = Field(default="statement")
597
+ tags: list[str] = Field(default_factory=list)
598
+
599
+ @field_validator("kind")
600
+ @classmethod
601
+ def valid_kind(cls, v: str) -> str:
602
+ from tortoise.domain_loader import known_kinds
603
+ allowed = known_kinds()
604
+ if v not in allowed:
605
+ raise ValueError(f"kind must be one of {sorted(allowed)}")
606
+ return v
607
+
608
+ @field_validator("tags")
609
+ @classmethod
610
+ def valid_tags(cls, v: list[str]) -> list[str]:
611
+ for t in v:
612
+ if not t or len(t) > 200:
613
+ raise ValueError("each tag must be 1-200 characters")
614
+ if any(ch in t for ch in '\n\r\t'):
615
+ raise ValueError("tags cannot contain newlines or tabs")
616
+ return v
617
+
618
+
619
+ class PointResponse(BaseModel):
620
+ id: str
621
+ content: str
622
+ kind: str
623
+ created_at: str | None = None
624
+
625
+
626
+ class TeamInfoResponse(BaseModel):
627
+ team_id: str
628
+ tier: str
629
+ max_users: int
630
+ max_graphs: int | None
631
+ max_teams: int | None
632
+ point_count: int = 0
633
+
634
+
635
+ class CreateKeyResponse(BaseModel):
636
+ id: str
637
+ key: str # plaintext — shown once
638
+ key_prefix: str
639
+ created_at: str
640
+
641
+
642
+ class KeyListResponse(BaseModel):
643
+ id: str
644
+ key_prefix: str
645
+ created_at: str | None
646
+ last_used_at: str | None
647
+ revoked_at: str | None
648
+
649
+
650
+ class ErrorResponse(BaseModel):
651
+ error: dict
652
+
653
+
654
+ # ── Onboarding: Pydantic Models (#498) ────────────────────────────
655
+
656
+ class RegisterRequest(BaseModel):
657
+ email: str = Field(..., min_length=5, max_length=254)
658
+ password: str = Field(..., min_length=8, max_length=128)
659
+
660
+ @field_validator("email")
661
+ @classmethod
662
+ def valid_email(cls, v: str) -> str:
663
+ import re
664
+ if not re.match(r'^[^@\s]+@[^@\s]+\.[^@\s]+$', v):
665
+ raise ValueError("Invalid email format")
666
+ return v.lower().strip()
667
+
668
+
669
+ class RegisterResponse(BaseModel):
670
+ api_key: str | None = None
671
+ team_id: str | None = None
672
+ graph_name: str | None = None
673
+ message: str | None = None # "already_registered" on duplicate
674
+
675
+
676
+ class OnboardingStateResponse(BaseModel):
677
+ onboarding: dict
678
+
679
+
680
+ class OnboardingStatePatchRequest(BaseModel):
681
+ github_connected: bool | None = None
682
+ github_org: str | None = None
683
+ github_connected_at: str | None = None
684
+ github_indexed: bool | None = None
685
+ github_index_job_id: str | None = None
686
+ session_recording: bool | None = None
687
+ demo_created: bool | None = None
688
+ team_created: bool | None = None
689
+
690
+
691
+ # ── Onboarding: Default State ─────────────────────────────────────
692
+
693
+ DEFAULT_ONBOARDING_STATE = {
694
+ "github_connected": False,
695
+ "github_org": None,
696
+ "github_connected_at": None,
697
+ "github_indexed": False,
698
+ "github_index_job_id": None,
699
+ "session_recording": False,
700
+ "demo_created": False,
701
+ "team_created": False,
702
+ "completed_at": None,
703
+ }
704
+
705
+
706
+ # ── IP-based Rate Limiter for /v1/register (#498) ─────────────────
707
+
708
+ _register_buckets: dict[str, list[float]] = defaultdict(list)
709
+ _register_lock = asyncio.Lock()
710
+ _REGISTER_MAX_PER_HOUR = 3
711
+
712
+
713
+ async def _check_register_rate_limit(request: Request) -> None:
714
+ """IP-based rate limit: 3 registrations per hour per IP."""
715
+ if os.environ.get("RATE_LIMIT_DISABLED") == "1":
716
+ return
717
+ if not request.client or not request.client.host:
718
+ return
719
+ ip = request.client.host
720
+ now = time.time()
721
+ async with _register_lock:
722
+ bucket = _register_buckets[ip]
723
+ bucket[:] = [t for t in bucket if now - t < 3600]
724
+ if len(bucket) >= _REGISTER_MAX_PER_HOUR:
725
+ raise HTTPException(
726
+ status_code=429,
727
+ detail="Too many registration attempts. Please try again later.",
728
+ headers={"Retry-After": "3600"},
729
+ )
730
+ bucket.append(now)
731
+
732
+
733
+ # ── Endpoints ─────────────────────────────────────────────────────
734
+
735
+ @app.post("/v1/points", response_model=PointResponse)
736
+ async def create_point(body: CreatePointRequest, request: Request, team: dict = Depends(get_current_team)):
737
+ """Create a Point in the team's graph."""
738
+ _check_team_limit(team, "points")
739
+ sdk = _make_sdk(namespace=team["team_id"])
740
+ try:
741
+ result = sdk.create_point(
742
+ content=body.content,
743
+ kind=body.kind,
744
+ tags=body.tags,
745
+ )
746
+ except HTTPException:
747
+ raise
748
+ except Exception as e:
749
+ import logging
750
+ logging.getLogger("tortoise.api").exception("create_point failed")
751
+ raise HTTPException(status_code=500, detail="Internal server error")
752
+ # Dreaming (#85): enqueue the new point's dirty roots for background EP
753
+ # stabilization (non-blocking — fast path is never gated on the dream).
754
+ _enqueue_dream(team["team_id"], list(sdk._dirty_roots))
755
+ # Log audit event
756
+ await _async_audit(
757
+ request, team["team_id"], "point_create",
758
+ resource_type="point", resource_id=result.get("id"),
759
+ )
760
+
761
+ return {
762
+ "id": result["id"],
763
+ "content": result["content"],
764
+ "kind": result.get("pointKind", result.get("kind", "")),
765
+ "created_at": result.get("createdAt", result.get("created_at", "")),
766
+ }
767
+
768
+
769
+ @app.get("/v1/points")
770
+ async def list_points(
771
+ kind: str | None = None,
772
+ tag: str | None = None,
773
+ limit: int = Query(50, ge=1, le=1000),
774
+ team: dict = Depends(get_current_team),
775
+ ):
776
+ """Query Points in the team's graph. Optional kind and tag filters."""
777
+ if kind:
778
+ from tortoise.domain_loader import known_kinds
779
+ allowed = known_kinds()
780
+ if kind not in allowed:
781
+ raise HTTPException(status_code=400, detail=f"kind must be one of {sorted(allowed)}")
782
+ sdk = _make_sdk(namespace=team["team_id"])
783
+ proj = sdk._get_proj()
784
+ conditions = ["(n.is_operator IS NULL OR n.is_operator = false)"]
785
+ params: dict = {"limit": limit}
786
+ if kind:
787
+ conditions.append("n.pointKind = $kind")
788
+ params["kind"] = kind
789
+ if tag:
790
+ # Query via TAGGED edges to :Tag nodes (#215)
791
+ tag_clause = "-[:TAGGED]->(t:Tag {name:$tag})"
792
+ params["tag"] = tag
793
+ else:
794
+ tag_clause = ""
795
+ query = (
796
+ f"MATCH (n:Point){tag_clause} WHERE "
797
+ + " AND ".join(conditions)
798
+ + " RETURN properties(n) ORDER BY n.createdAt DESC LIMIT $limit"
799
+ )
800
+ rows = proj.g.query(query, params=params).result_set
801
+ results = []
802
+ for r in rows:
803
+ d = r[0]
804
+ if "pointKind" in d:
805
+ d["kind"] = d.pop("pointKind")
806
+ results.append(d)
807
+ return {"points": results, "count": len(results)}
808
+
809
+
810
+ @app.get("/v1/points/{point_id}")
811
+ async def get_point(point_id: str, team: dict = Depends(get_current_team)):
812
+ """Get a single Point by ID."""
813
+ sdk = _make_sdk(namespace=team["team_id"])
814
+ proj = sdk._get_proj()
815
+ rows = proj.g.query(
816
+ "MATCH (p:Point {id: $id}) RETURN properties(p)",
817
+ params={"id": point_id},
818
+ ).result_set
819
+ if not rows:
820
+ raise HTTPException(status_code=404, detail="Point not found")
821
+ props = dict(rows[0][0])
822
+ if "pointKind" in props:
823
+ props["kind"] = props.pop("pointKind")
824
+ return props
825
+
826
+
827
+ @app.post("/v1/dream")
828
+ async def dream(
829
+ full: bool = False,
830
+ team: dict = Depends(get_current_team),
831
+ ):
832
+ """Trigger EP stabilization (dreaming, #85) for the team's graph.
833
+
834
+ Incremental (default): stabilizes the team's accumulated dirty subgraph.
835
+ full=True: whole-graph stabilization. Fast-path queries never block on
836
+ this — dreaming is a background maintenance process.
837
+ """
838
+ # #329: full-graph EP stabilization is CPU-heavy; per-key rate limiting is
839
+ # NOT the bound (tenants can hold up to max_api_keys keys). Per-team hourly
840
+ # budget MAX_DREAM_FULL_PER_HOUR for full=True; incremental is cheap.
841
+ import time as _t
842
+ from tortoise.quota import MAX_DREAM_FULL_PER_HOUR
843
+ if full:
844
+ tid = team["team_id"]
845
+ now_ts = _t.time()
846
+ bucket = _DREAM_FULL_BUCKETS.setdefault(tid, [])
847
+ bucket[:] = [ts for ts in bucket if now_ts - ts < 3600]
848
+ # prune -> check -> append (never pop between check and append — that
849
+ # orphans the appended timestamp and silently disables the budget)
850
+ if len(bucket) >= MAX_DREAM_FULL_PER_HOUR:
851
+ raise HTTPException(
852
+ status_code=429,
853
+ detail=f"Full-graph dream budget exhausted ({MAX_DREAM_FULL_PER_HOUR}/hour). "
854
+ "Try incremental dreaming or wait.",
855
+ )
856
+ bucket.append(now_ts)
857
+
858
+ sdk = _make_sdk(namespace=team["team_id"])
859
+ try:
860
+ if full:
861
+ result = sdk.dream(full=True)
862
+ else:
863
+ # Drain whatever is queued plus any in-memory dirty roots.
864
+ # Batch mark once (P3, #85) — one reverse-BFS pair, not N.
865
+ q = _DREAM_QUEUES.get(team["team_id"])
866
+ queued_roots: list[str] = []
867
+ if q is not None and not q.empty():
868
+ while not q.empty():
869
+ queued_roots.append(q.get_nowait())
870
+ if queued_roots:
871
+ sdk._mark_dirty(queued_roots)
872
+ result = sdk.dream(dirty_only=True)
873
+ return result
874
+ finally:
875
+ sdk.close()
876
+
877
+
878
+ @app.get("/v1/search")
879
+ async def search(q: str, limit: int = Query(10, ge=1, le=100), team: dict = Depends(get_current_team)):
880
+ """Hybrid search across Points (FTS + vector + structural, RRF-fused).
881
+
882
+ Uses the SDK's tortoise_fts_query (search_engine) instead of raw
883
+ substring CONTAINS — substring missed stemmed/fuzzy/typo matches and
884
+ was not relevance-ranked (#160). FTS index on content/title/name/subject
885
+ works without the embedding extra; vector joins in automatically when
886
+ embeddings are available.
887
+ """
888
+ sdk = _make_sdk(namespace=team["team_id"])
889
+ try:
890
+ results = sdk.tortoise_fts_query(q, limit=limit)
891
+ except Exception:
892
+ import logging
893
+ logging.getLogger("tortoise.api").exception("search failed")
894
+ raise HTTPException(status_code=500, detail="Search failed")
895
+ # Normalize to the public response shape (kind from pointKind).
896
+ out = []
897
+ for r in results:
898
+ props = dict(r)
899
+ if "pointKind" in props:
900
+ props["kind"] = props.pop("pointKind")
901
+ if "kind" not in props:
902
+ props["kind"] = "statement"
903
+ out.append(props)
904
+ return {"results": out, "count": len(out)}
905
+
906
+
907
+ @app.get("/v1/team", response_model=TeamInfoResponse)
908
+ async def team_info(team: dict = Depends(get_current_team)):
909
+ """Get current team info: tier, usage, limits."""
910
+ sdk = _make_sdk(namespace=team["team_id"])
911
+ # Count Points in default graph
912
+ try:
913
+ point_count = sdk._get_proj().g.query(
914
+ "MATCH (n:Point) RETURN count(n)"
915
+ ).result_set[0][0]
916
+ except Exception as e:
917
+ import logging
918
+ logging.getLogger("tortoise.api").exception("team_info failed")
919
+ raise HTTPException(status_code=500, detail="Internal server error")
920
+
921
+ return TeamInfoResponse(
922
+ team_id=team["team_id"],
923
+ tier=team["tier"],
924
+ max_users=team["max_users"],
925
+ max_graphs=team["max_graphs"],
926
+ max_teams=team["max_teams"],
927
+ point_count=point_count,
928
+ )
929
+
930
+
931
+ # ── Onboarding: Self-Service Registration (#498) ──────────────────
932
+
933
+ @app.post("/v1/register", response_model=RegisterResponse)
934
+ async def register_user(request: Request, response: Response):
935
+ """Self-service key provisioning — public variant of /internal/provision.
936
+
937
+ Creates a Team node + API key + tenant graph in FalkorDB. Does NOT
938
+ create a Supabase user (that's handled separately by the welcome page
939
+ via Supabase client-side auth). Rate limited at 3 registrations/hour/IP.
940
+ """
941
+ await _check_register_rate_limit(request)
942
+
943
+ body = await request.json()
944
+ try:
945
+ reg = RegisterRequest.model_validate(body)
946
+ except Exception as e:
947
+ raise HTTPException(status_code=422, detail=str(e))
948
+
949
+ email = reg.email
950
+ password = reg.password # noqa: F841 — validated, not stored (Supabase handles auth)
951
+
952
+ # Idempotency: check if email already registered via Team node property
953
+ sdk_check = _make_sdk(namespace="registry")
954
+ existing = sdk_check._get_registry().query(
955
+ "MATCH (t:Team) WHERE t.email = $email RETURN t.id",
956
+ params={"email": email},
957
+ ).result_set
958
+ if existing:
959
+ raise HTTPException(
960
+ status_code=409,
961
+ detail={"message": "already_registered", "email": email},
962
+ )
963
+
964
+ # Derive team_id from email (slugified)
965
+ import re
966
+ team_name = email.split("@")[0]
967
+ team_name = re.sub(r'[^a-zA-Z0-9_-]', '-', team_name)[:48]
968
+ team_id = _short_id()
969
+
970
+ # Generate API key
971
+ import uuid
972
+ from tortoise.auth import hash_api_key
973
+ api_key = f"tt_{uuid.uuid4().hex}"
974
+ key_hash = hash_api_key(api_key)
975
+ sdk = _make_sdk(namespace="registry")
976
+ now = datetime.now(timezone.utc).isoformat()
977
+ graph_name = f"team_{team_id}"
978
+
979
+ try:
980
+ # Create Team node with email and default onboarding state
981
+ sdk._get_registry().query(
982
+ """
983
+ CREATE (t:Team {
984
+ id: $id, name: $name, email: $email, tier: 'free',
985
+ created_at: $now, backup_enabled: false,
986
+ max_users: 1, max_teams: 1, max_graphs: 1,
987
+ onboarding_state: $onboarding_state
988
+ })
989
+ """,
990
+ params={
991
+ "id": team_id, "name": team_name, "email": email,
992
+ "now": now, "onboarding_state": _json.dumps(DEFAULT_ONBOARDING_STATE),
993
+ },
994
+ )
995
+
996
+ # Create APIKey node
997
+ api_key_id = _short_id()
998
+ sdk._get_registry().query(
999
+ """
1000
+ CREATE (k:APIKey {
1001
+ id: $id, team_id: $team_id, key_hash: $hash,
1002
+ key_prefix: $prefix, created_by: $created_by,
1003
+ created_at: $now
1004
+ })
1005
+ """,
1006
+ params={
1007
+ "id": api_key_id,
1008
+ "team_id": team_id,
1009
+ "hash": key_hash,
1010
+ "prefix": team_id[:8],
1011
+ "created_by": email,
1012
+ "now": now,
1013
+ },
1014
+ )
1015
+
1016
+ # Provision FalkorDB namespace for the team
1017
+ team_graph = sdk._get_proj().db.select_graph(graph_name)
1018
+ team_graph.query(
1019
+ "CREATE (:TeamMeta {name: $name, created: $now})",
1020
+ params={"name": team_name, "now": now},
1021
+ )
1022
+
1023
+ # Log audit event
1024
+ await _async_audit(
1025
+ request, team_id, "tenant_register",
1026
+ resource_type="team", resource_id=team_id,
1027
+ )
1028
+
1029
+ response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
1030
+
1031
+ return {"api_key": api_key, "team_id": team_id, "graph_name": graph_name}
1032
+
1033
+ except HTTPException:
1034
+ raise
1035
+ except Exception:
1036
+ # Rollback on failure
1037
+ sdk._get_registry().query(
1038
+ "MATCH (t:Team {id: $id}) DETACH DELETE t", params={"id": team_id}
1039
+ )
1040
+ sdk._get_registry().query(
1041
+ "MATCH (k:APIKey {team_id: $id}) DETACH DELETE k", params={"id": team_id}
1042
+ )
1043
+ try:
1044
+ team_graph = sdk._get_proj().db.select_graph(graph_name)
1045
+ team_graph.delete()
1046
+ except Exception:
1047
+ pass
1048
+ raise HTTPException(status_code=500, detail="Registration failed")
1049
+
1050
+
1051
+ def _seed_demo_graph(team_id: str) -> dict:
1052
+ """Seed the 4-layer demo graph for a team. Idempotent (sentinel)."""
1053
+ sdk = _make_sdk(namespace=team_id)
1054
+ proj = sdk._get_proj()
1055
+ now = datetime.now(timezone.utc).isoformat()
1056
+
1057
+ # Idempotency: sentinel written last — skip if already fully seeded
1058
+ existing = proj.g.query(
1059
+ "MATCH (p:Point {id: '_demo_sentinel'}) RETURN p.id"
1060
+ ).result_set
1061
+ if existing:
1062
+ return {"status": "already_seeded", "team_id": team_id}
1063
+
1064
+ # ── Semantic Layer — facts and statements ────────────────────
1065
+ semantic_points = [
1066
+ ("sem_welcome", "observation",
1067
+ "Your Tortoise graph is ready. This is where agents file decisions, "
1068
+ "observations, and findings so your team remembers across sessions.",
1069
+ ["system", "welcome"]),
1070
+ ("sem_fact_tortoise", "statement",
1071
+ "Tortoise is a semantic epistemic graph engine that powers agent memory "
1072
+ "through four ontology layers: Semantic, Episodic, Epistemic, and Procedural.",
1073
+ ["tortoise", "overview"]),
1074
+ ("sem_fact_layers", "statement",
1075
+ "Semantic = facts and statements. Episodic = session history and events. "
1076
+ "Epistemic = claims with evidence and confidence. Procedural = workflows and skills.",
1077
+ ["tortoise", "ontology"]),
1078
+ ]
1079
+ for pid, kind, content, tags in semantic_points:
1080
+ proj.g.query(
1081
+ "MERGE (p:Point {id:$id}) "
1082
+ "SET p.content=$c, p.pointKind=$k, p.is_operator=false, "
1083
+ "p.status='live', p.createdAt=$now, p.updatedAt=$now",
1084
+ params={"id": pid, "c": content, "k": kind, "now": now},
1085
+ )
1086
+ for tag in tags:
1087
+ proj.g.query(
1088
+ "MATCH (p:Point {id:$pid}) "
1089
+ "MERGE (t:Tag {name:$tag}) "
1090
+ "MERGE (p)-[:TAGGED]->(t)",
1091
+ params={"pid": pid, "tag": tag},
1092
+ )
1093
+
1094
+ # ── Episodic Layer — session events ──────────────────────────
1095
+ session_id = f"session_demo_{team_id[:8]}"
1096
+ proj.g.query(
1097
+ "MERGE (s:Session {id:$sid}) "
1098
+ "SET s.created_at=$now, s.turn_count=3",
1099
+ params={"sid": session_id, "now": now},
1100
+ )
1101
+ episodic_turns = [
1102
+ ("epi_turn1", "[user] Let's set up our agent memory system with Tortoise."),
1103
+ ("epi_turn2", "[assistant] I'll initialize the graph and configure the ontology layers. "
1104
+ "Once set up, all decisions will be tracked automatically."),
1105
+ ("epi_turn3", "[user] Great — make sure we capture decisions about architecture and product strategy."),
1106
+ ]
1107
+ for pid, content in episodic_turns:
1108
+ proj.g.query(
1109
+ "MERGE (t:Point {id:$id}) "
1110
+ "SET t.content=$c, t.pointKind='event', t.is_operator=false, "
1111
+ "t.status='live', t.createdAt=$now, t.updatedAt=$now",
1112
+ params={"id": pid, "c": content, "now": now},
1113
+ )
1114
+ proj.g.query(
1115
+ "MATCH (s:Session {id:$sid}), (t:Point {id:$pid}) "
1116
+ "MERGE (s)-[:CONTAINS]->(t)",
1117
+ params={"sid": session_id, "pid": pid},
1118
+ )
1119
+
1120
+ # ── Epistemic Layer — claims with evidence ───────────────────
1121
+ epistemic_points = [
1122
+ ("epis_claim1", "hypothesis",
1123
+ "Agent memory systems should be graph-native rather than vector-only "
1124
+ "because semantic relationships carry more signal than embedding proximity.",
1125
+ 0.7, ["hypothesis", "architecture"]),
1126
+ ("epis_claim2", "evidence",
1127
+ "Teams using structured agent memory report 40% fewer repeated mistakes "
1128
+ "and 3x faster onboarding for new team members.",
1129
+ 0.5, ["evidence", "adoption"]),
1130
+ ("epis_claim3", "decision",
1131
+ "We will use FalkorDB as the graph backend because it supports Cypher "
1132
+ "queries and runs as a lightweight extension to Redis.",
1133
+ 0.9, ["decision", "infrastructure"]),
1134
+ ]
1135
+ for pid, kind, content, confidence, tags in epistemic_points:
1136
+ proj.g.query(
1137
+ "MERGE (p:Point {id:$id}) "
1138
+ "SET p.content=$c, p.pointKind=$k, p.is_operator=false, "
1139
+ "p.status='live', p.confidence=$conf, p.createdAt=$now, p.updatedAt=$now",
1140
+ params={"id": pid, "c": content, "k": kind, "conf": confidence, "now": now},
1141
+ )
1142
+ for tag in tags:
1143
+ proj.g.query(
1144
+ "MATCH (p:Point {id:$pid}) "
1145
+ "MERGE (t:Tag {name:$tag}) "
1146
+ "MERGE (p)-[:TAGGED]->(t)",
1147
+ params={"pid": pid, "tag": tag},
1148
+ )
1149
+
1150
+ # ── Procedural Layer — workflows ─────────────────────────────
1151
+ procedural_points = [
1152
+ ("proc_wf1", "workflow",
1153
+ "CONTEXT-INJECTION: Before any coding task, call tortoise_suggest_entry_points() "
1154
+ "to find related context from past sessions and decisions.",
1155
+ ["workflow", "context"]),
1156
+ ("proc_wf2", "workflow",
1157
+ "DECISION-CAPTURE: After making a design decision, call tortoise_create_point() "
1158
+ "with kind='decision' so future agents can trace the reasoning chain.",
1159
+ ["workflow", "decision"]),
1160
+ ("proc_wf3", "workflow",
1161
+ "REVIEW-GATE: Before merging any PR, verify that key decisions are filed in Tortoise. "
1162
+ "If not, file them before merging.",
1163
+ ["workflow", "review"]),
1164
+ ]
1165
+ for pid, kind, content, tags in procedural_points:
1166
+ proj.g.query(
1167
+ "MERGE (p:Point {id:$id}) "
1168
+ "SET p.content=$c, p.pointKind=$k, p.is_operator=false, "
1169
+ "p.status='live', p.createdAt=$now, p.updatedAt=$now",
1170
+ params={"id": pid, "c": content, "k": kind, "now": now},
1171
+ )
1172
+ for tag in tags:
1173
+ proj.g.query(
1174
+ "MATCH (p:Point {id:$pid}) "
1175
+ "MERGE (t:Tag {name:$tag}) "
1176
+ "MERGE (p)-[:TAGGED]->(t)",
1177
+ params={"pid": pid, "tag": tag},
1178
+ )
1179
+
1180
+ # ── Cross-layer links ────────────────────────────────────────
1181
+ # Link epistemic claim to supporting semantic fact
1182
+ proj.g.query(
1183
+ "MATCH (c:Point {id:'epis_claim1'}), (f:Point {id:'sem_fact_layers'}) "
1184
+ "MERGE (c)-[:SUPPORTS]->(f)"
1185
+ )
1186
+ # Link workflow to epistemic claim
1187
+ proj.g.query(
1188
+ "MATCH (w:Point {id:'proc_wf1'}), (c:Point {id:'epis_claim1'}) "
1189
+ "MERGE (w)-[:INFORMED_BY]->(c)"
1190
+ )
1191
+
1192
+ # ── Sentinel — written last so partial failure allows retry ──
1193
+ proj.g.query(
1194
+ "CREATE (p:Point {id:'_demo_sentinel', content:'demo-sentinel', "
1195
+ "pointKind:'system', is_operator:false, status:'live', "
1196
+ "createdAt:$now, updatedAt:$now})",
1197
+ params={"now": now},
1198
+ )
1199
+
1200
+ total_points = (
1201
+ len(semantic_points) + len(episodic_turns)
1202
+ + len(epistemic_points) + len(procedural_points)
1203
+ )
1204
+ return {
1205
+ "status": "demo_created",
1206
+ "team_id": team_id,
1207
+ "session_id": session_id,
1208
+ "points": total_points,
1209
+ "layers": {
1210
+ "semantic": len(semantic_points),
1211
+ "episodic": len(episodic_turns),
1212
+ "epistemic": len(epistemic_points),
1213
+ "procedural": len(procedural_points),
1214
+ },
1215
+ }
1216
+
1217
+
1218
+
1219
+
1220
+ @app.post("/internal/demo")
1221
+ async def create_demo_graph(request: Request):
1222
+ """Create a demo graph with sample Points across all 4 ontology layers.
1223
+
1224
+ Called by the tenant-provision Edge Function after provisioning to seed
1225
+ demo data so new users see a populated graph immediately.
1226
+ """
1227
+ _check_internal(request)
1228
+
1229
+ body = await request.json()
1230
+ team_id = body.get("team_id")
1231
+ if not team_id:
1232
+ raise HTTPException(status_code=400, detail="Missing team_id")
1233
+
1234
+ return _seed_demo_graph(team_id)
1235
+
1236
+ @app.post("/v1/team/keys", response_model=CreateKeyResponse)
1237
+ async def create_api_key(request: Request, response: Response, team: dict = Depends(get_current_team)):
1238
+ """Generate a new API key for the team."""
1239
+ _check_team_limit(team, "api_keys")
1240
+ import uuid
1241
+ from tortoise.auth import hash_api_key
1242
+ sdk = _make_sdk(namespace="registry")
1243
+ api_key = f"tt_{uuid.uuid4().hex}"
1244
+ key_hash = hash_api_key(api_key)
1245
+ key_prefix = api_key[:10]
1246
+ kid = _short_id()
1247
+ now = datetime.now(timezone.utc).isoformat()
1248
+ sdk._get_registry().query(
1249
+ "CREATE (k:APIKey {id:$id, team_id:$tid, key_hash:$kh, key_prefix:$kp, created_by:$cb, created_at:$now})",
1250
+ params={"id": kid, "tid": team["team_id"], "kh": key_hash, "kp": key_prefix, "cb": "api", "now": now},
1251
+ )
1252
+ # Log audit event
1253
+ await _async_audit(
1254
+ request, team["team_id"], "api_key_create",
1255
+ resource_type="api_key", resource_id=kid,
1256
+ )
1257
+
1258
+ response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
1259
+
1260
+ return {
1261
+ "id": kid,
1262
+ "key": api_key,
1263
+ "key_prefix": key_prefix,
1264
+ "created_at": now,
1265
+ }
1266
+
1267
+
1268
+ @app.get("/v1/team/keys")
1269
+ async def list_api_keys(team: dict = Depends(get_current_team)):
1270
+ """List API keys for the team (hashes only — no plaintext)."""
1271
+ sdk = _make_sdk(namespace="registry")
1272
+ try:
1273
+ keys = sdk._get_registry().query(
1274
+ "MATCH (k:APIKey {team_id: $tid}) "
1275
+ "RETURN k.id, k.key_prefix, k.created_at, k.last_used_at, k.revoked_at "
1276
+ "ORDER BY k.created_at DESC",
1277
+ params={"tid": team["team_id"]},
1278
+ )
1279
+ except Exception as e:
1280
+ import logging
1281
+ logging.getLogger("tortoise.api").exception("list_api_keys failed")
1282
+ raise HTTPException(status_code=500, detail="Internal server error")
1283
+ return {
1284
+ "keys": [
1285
+ {
1286
+ "id": row[0],
1287
+ "key_prefix": row[1],
1288
+ "created_at": row[2],
1289
+ "last_used_at": row[3],
1290
+ "revoked_at": row[4],
1291
+ }
1292
+ for row in keys.result_set
1293
+ ]
1294
+ }
1295
+
1296
+
1297
+
1298
+
1299
+ @app.delete("/v1/team/keys/{key_id}")
1300
+ async def revoke_api_key(key_id: str, team: dict = Depends(get_current_team)):
1301
+ """Revoke an API key (soft delete — sets revoked_at). Team-scoped.
1302
+
1303
+ Keys live in the control_plane registry graph (per #7873) — created via
1304
+ POST /v1/team/keys, listed via GET /v1/team/keys, revoked here, all on
1305
+ _get_registry(), consistent with the SDK's control-plane methods.
1306
+ """
1307
+ sdk = _make_sdk(namespace="registry")
1308
+ try:
1309
+ rows = sdk._get_registry().query(
1310
+ "MATCH (k:APIKey {id: $id}) RETURN k.team_id, k.revoked_at",
1311
+ params={"id": key_id},
1312
+ ).result_set
1313
+ if not rows:
1314
+ raise HTTPException(status_code=404, detail="API key not found")
1315
+ if rows[0][0] != team["team_id"]:
1316
+ raise HTTPException(status_code=403, detail="Not your API key")
1317
+ if rows[0][1] is not None:
1318
+ return {"revoked": True, "already": True, "key_id": key_id}
1319
+ from datetime import datetime, timezone
1320
+ now = datetime.now(timezone.utc).isoformat()
1321
+ sdk._get_registry().query(
1322
+ "MATCH (k:APIKey {id: $id}) SET k.revoked_at = $now",
1323
+ params={"id": key_id, "now": now},
1324
+ )
1325
+ except HTTPException:
1326
+ raise
1327
+ except Exception as e:
1328
+ import logging
1329
+ logging.getLogger("tortoise.api").exception("revoke_api_key failed")
1330
+ raise HTTPException(status_code=500, detail="Internal server error")
1331
+ return {"revoked": True, "key_id": key_id, "revoked_at": now}
1332
+ # ── Session Capture ───────────────────────────────────────────────
1333
+
1334
+ class SessionRequest(BaseModel):
1335
+ conversation: list[dict] = Field(..., max_length=1000)
1336
+
1337
+ @field_validator("conversation")
1338
+ @classmethod
1339
+ def valid_conversation(cls, v: list[dict]) -> list[dict]:
1340
+ for turn in v:
1341
+ content = turn.get("content", "")
1342
+ if len(content) > 5000:
1343
+ raise ValueError("each conversation turn content must be ≤ 5000 characters")
1344
+ return v
1345
+ session_id: str | None = None
1346
+ metadata: dict | None = None
1347
+
1348
+
1349
+ @app.post("/v1/sessions")
1350
+ async def capture_session(body: SessionRequest, request: Request, team: dict = Depends(get_current_team)):
1351
+ """Capture an agent session and extract turns as episodic Points.
1352
+
1353
+ #329 flood gate: the extraction amplifier creates ~160 nodes/turn via the
1354
+ decision/claim regexes (empirically 30 dense turns → 4,832 nodes) and the
1355
+ ``sessions`` quota counts TOTAL nodes (MATCH (n), matching REST's
1356
+ historical semantics) — Points were unbounded. Bounds (checked in order):
1357
+ per-request turn cap → 400; extraction-aware pre-write estimate vs the
1358
+ points quota → 402; per-turn extraction cap (in the loop).
1359
+ """
1360
+ import uuid, re
1361
+ from datetime import datetime, timezone
1362
+ from tortoise.quota import (
1363
+ MAX_EXTRACTIONS_PER_TURN, MAX_SESSION_TURNS,
1364
+ QuotaCheckError, QuotaExceededError, enforce_team_limit,
1365
+ )
1366
+
1367
+ if len(body.conversation) > MAX_SESSION_TURNS:
1368
+ raise HTTPException(
1369
+ status_code=400,
1370
+ detail=f"Session turn cap exceeded: {len(body.conversation)} > {MAX_SESSION_TURNS}.",
1371
+ )
1372
+
1373
+ # Extraction-aware estimate (pre-write, fail-closed count):
1374
+ # est = 1 Session + 1 Event + Σ_turns (1 turn Point
1375
+ # + min(decisions, cap) + min(claims, cap))
1376
+ decisions = [
1377
+ r"(?i)(?:let'?s|we will|we should|I will|I'm going to|decided|decision)\s+[^.!?]+[.!?]",
1378
+ r"(?i)(?:plan is|next steps?:|action item:)\s+[^.!?]+[.!?]",
1379
+ ]
1380
+ claims = [
1381
+ r"(?i)(?:I think|I believe|my understanding is|the problem is|the key insight)\s+[^.!?]+[.!?]",
1382
+ r"(?i)(?:evidence suggests|data shows|we found that|this means)\s+[^.!?]+[.!?]",
1383
+ ]
1384
+ est = 2
1385
+ for turn in body.conversation:
1386
+ # #329: estimate scans the SAME full content the extraction loop uses
1387
+ # (must be an upper bound — a truncation mismatch would under-count).
1388
+ content = turn.get("content", "")
1389
+ n_dec = sum(len(re.findall(p, content)) for p in decisions)
1390
+ n_clm = sum(len(re.findall(p, content)) for p in claims)
1391
+ est += 1 + min(n_dec, MAX_EXTRACTIONS_PER_TURN) + min(n_clm, MAX_EXTRACTIONS_PER_TURN)
1392
+ from tortoise.quota import count_team_usage
1393
+ sdk_team = _make_sdk(namespace=team["team_id"])
1394
+ try:
1395
+ count = count_team_usage(team["team_id"], "points", sdk=sdk_team)
1396
+ except QuotaCheckError as e:
1397
+ raise HTTPException(status_code=500, detail=f"Quota check failed: {e}")
1398
+ max_points = team.get("max_points") or 1000
1399
+ if count + est > max_points:
1400
+ raise HTTPException(
1401
+ status_code=402,
1402
+ detail=f"Team points limit reached: {count} in use + {est} estimated "
1403
+ f"for this capture exceeds {max_points}. Upgrade your plan.",
1404
+ )
1405
+
1406
+ _check_team_limit(team, "sessions")
1407
+ sdk = _make_sdk(namespace=team["team_id"])
1408
+ proj = sdk._get_proj()
1409
+ session_id = body.session_id or f"session_{uuid.uuid4().hex[:12]}"
1410
+ now = datetime.now(timezone.utc).isoformat()
1411
+
1412
+ proj.g.query(
1413
+ "MERGE (s:Session {id:$sid}) SET s.created_at=$now, s.turn_count=$tc",
1414
+ params={"sid": session_id, "now": now, "tc": len(body.conversation)},
1415
+ )
1416
+
1417
+ extracted = []
1418
+
1419
+ for i, turn in enumerate(body.conversation):
1420
+ role = turn.get("role", "unknown")
1421
+ content = turn.get("content", "")
1422
+
1423
+ # #490: turn Points are the episodic turn stream OF THIS SESSION —
1424
+ # keyed deterministically by {session_id}_t{i} so re-capturing the
1425
+ # same session is idempotent, but turns from different sessions never
1426
+ # conflate (content-hash dedup would share an empty "[user] " or
1427
+ # repeated "ok" turn team-wide, destroying per-session turn identity
1428
+ # — #490 review P2-2). Node MERGEs run BEFORE the edge MERGE: a full-
1429
+ # path MERGE (s)-[:CONTAINS]->(t) with a missing edge makes FalkorDB
1430
+ # create the whole path from scratch, duplicating the Point node.
1431
+ turn_id = f"{session_id}_t{i}"
1432
+ turn_text = f"[{role}] {content[:5000]}"
1433
+ proj.g.query(
1434
+ "MERGE (t:Point {id:$id}) "
1435
+ "SET t.content=$c, t.pointKind=$k, t.is_operator=false, "
1436
+ " t.status=coalesce(t.status, $s), "
1437
+ " t.createdAt=coalesce(t.createdAt, $now), "
1438
+ " t.updatedAt=$now, t.content_hash=$ch",
1439
+ params={"id": turn_id, "c": turn_text, "k": "event",
1440
+ "s": "draft", "now": now, "ch": _content_hash(turn_text)},
1441
+ )
1442
+ proj.g.query(
1443
+ "MATCH (s:Session {id:$sid}), (t:Point {id:$tid}) "
1444
+ "MERGE (s)-[:CONTAINS]->(t)",
1445
+ params={"sid": session_id, "tid": turn_id},
1446
+ )
1447
+
1448
+ # #329: per-turn extraction cap (matches the estimate's min() bound —
1449
+ # without it a single dense turn writes thousands of Points).
1450
+ n_dec_extracted = 0
1451
+ for pat in decisions:
1452
+ for match in re.finditer(pat, content):
1453
+ if n_dec_extracted >= MAX_EXTRACTIONS_PER_TURN:
1454
+ break
1455
+ n_dec_extracted += 1
1456
+ text = match.group().strip()
1457
+ # Extracted decisions/claims ARE cross-session knowledge —
1458
+ # keep content-hash dedup (identical claim in two sessions is
1459
+ # one Point). Dedup by content_hash + pointKind via SDK.
1460
+ p = sdk.create_point("decision", text[:5000], dedup=True)
1461
+ pid = p["id"]
1462
+ proj.g.query(
1463
+ "MATCH (s:Session {id:$sid}), (p:Point {id:$pid}) "
1464
+ "MERGE (s)-[:CONTAINS]->(p)",
1465
+ params={"sid": session_id, "pid": pid},
1466
+ )
1467
+ extracted.append({"id": pid, "kind": "decision", "text": text[:200]})
1468
+
1469
+ n_clm_extracted = 0
1470
+ for pat in claims:
1471
+ for match in re.finditer(pat, content):
1472
+ if n_clm_extracted >= MAX_EXTRACTIONS_PER_TURN:
1473
+ break
1474
+ n_clm_extracted += 1
1475
+ text = match.group().strip()
1476
+ p = sdk.create_point("statement", text[:5000], dedup=True)
1477
+ pid = p["id"]
1478
+ proj.g.query(
1479
+ "MATCH (s:Session {id:$sid}), (p:Point {id:$pid}) "
1480
+ "MERGE (s)-[:CONTAINS]->(p)",
1481
+ params={"sid": session_id, "pid": pid},
1482
+ )
1483
+ extracted.append({"id": pid, "kind": "statement", "text": text[:200]})
1484
+
1485
+ # Ontology v3.1 §4.5/§3.2 (#7882): also create an episodic :Event node
1486
+ # (eventKind: sessionCaptured) and link extracted Points to it via
1487
+ # aboutEvent — the ontology's episodic model. The :Session node remains
1488
+ # the API-visible handle; the Event carries ontology-compliant provenance.
1489
+ try:
1490
+ event = sdk.create_event(
1491
+ f"session_{session_id}",
1492
+ "sessionCaptured",
1493
+ startedAt=now,
1494
+ endedAt=now,
1495
+ sessionId=session_id,
1496
+ )
1497
+ event_id = event.get("id") or event.get("eventId")
1498
+ for p in extracted:
1499
+ proj.create_about_edge(p["id"], event_id, "aboutEvent")
1500
+ except Exception:
1501
+ import logging
1502
+ logging.getLogger("tortoise.api").exception(
1503
+ "session Event creation failed (non-fatal)")
1504
+
1505
+ # Log audit event
1506
+ await _async_audit(
1507
+ request, team["team_id"], "session_capture",
1508
+ resource_type="session", resource_id=session_id,
1509
+ )
1510
+
1511
+ return {"session_id": session_id, "turns": len(body.conversation), "extracted": len(extracted), "points": extracted}
1512
+
1513
+
1514
+ @app.get("/v1/sessions")
1515
+ async def list_sessions(team: dict = Depends(get_current_team)):
1516
+ """List captured sessions."""
1517
+ sdk = _make_sdk(namespace=team["team_id"])
1518
+ proj = sdk._get_proj()
1519
+ rows = proj.g.query(
1520
+ "MATCH (s:Session) RETURN s.id, s.created_at, s.turn_count ORDER BY s.created_at DESC LIMIT 50"
1521
+ ).result_set
1522
+ return {"sessions": [{"id": r[0], "created_at": r[1], "turns": r[2]} for r in rows]}
1523
+
1524
+
1525
+ @app.get("/v1/context")
1526
+ async def session_context(team: dict = Depends(get_current_team)):
1527
+ """Memory digest for agent session-start hooks (tortoise context CLI).
1528
+
1529
+ Mirrors TortoiseSDK.session_context() so hosted users get the same
1530
+ injection payload as local users.
1531
+ """
1532
+ sdk = _make_sdk(namespace=team["team_id"])
1533
+ try:
1534
+ return sdk.session_context()
1535
+ except Exception as e:
1536
+ raise HTTPException(status_code=500, detail=f"Context unavailable: {e}")
1537
+
1538
+
1539
+
1540
+ # ── Onboarding endpoints (#498) ─────────────────────────────────
1541
+
1542
+ _ONBOARDING_DEFAULT_STATE = {
1543
+ "github_connected": False,
1544
+ "github_indexed": False,
1545
+ "demo_created": False,
1546
+ "session_recording": False,
1547
+ "team_created": False,
1548
+ "prompt_pasted": False,
1549
+ "onboarding_complete": False,
1550
+ }
1551
+
1552
+ _ALLOWED_STATE_KEYS = set(_ONBOARDING_DEFAULT_STATE.keys())
1553
+
1554
+
1555
+ def _get_onboarding_state(team_id: str) -> dict:
1556
+ """Read onboarding_state from the Team node in the registry graph.
1557
+
1558
+ Auto-initializes to defaults if missing (plan Task 3 — missing state
1559
+ auto-initializes on first read). Stored as a JSON string (FalkorDB
1560
+ properties are primitives-only — dicts raise ResponseError).
1561
+ """
1562
+ import json as _json
1563
+ sdk = _make_sdk(namespace="registry")
1564
+ rows = sdk._get_registry().query(
1565
+ "MATCH (t:Team {id: $id}) RETURN t.onboarding_state",
1566
+ params={"id": team_id},
1567
+ ).result_set
1568
+ if not rows or rows[0][0] is None:
1569
+ state = dict(_ONBOARDING_DEFAULT_STATE)
1570
+ _write_onboarding_state(team_id, state)
1571
+ return state
1572
+ try:
1573
+ stored = _json.loads(rows[0][0]) if isinstance(rows[0][0], str) else rows[0][0]
1574
+ except (TypeError, ValueError):
1575
+ stored = {}
1576
+ state = dict(_ONBOARDING_DEFAULT_STATE)
1577
+ state.update(stored)
1578
+ return state
1579
+
1580
+
1581
+ def _write_onboarding_state(team_id: str, state: dict) -> None:
1582
+ """Persist onboarding_state on the Team node (JSON string — #498 fix:
1583
+ FalkorDB node properties must be primitives, not dicts)."""
1584
+ import json as _json
1585
+ sdk = _make_sdk(namespace="registry")
1586
+ sdk._get_registry().query(
1587
+ "MATCH (t:Team {id: $id}) SET t.onboarding_state = $state",
1588
+ params={"id": team_id, "state": _json.dumps(state)},
1589
+ )
1590
+
1591
+
1592
+ def _update_onboarding_state(team_id: str, **fields) -> dict:
1593
+ """Merge fields into onboarding state and persist. Returns new state."""
1594
+ state = _get_onboarding_state(team_id)
1595
+ for k, v in fields.items():
1596
+ if k in _ALLOWED_STATE_KEYS:
1597
+ state[k] = v
1598
+ _write_onboarding_state(team_id, state)
1599
+ return state
1600
+
1601
+
1602
+ class OnboardingStateResponse(BaseModel):
1603
+ onboarding: dict
1604
+
1605
+
1606
+ class OnboardingStatePatchRequest(BaseModel):
1607
+ github_connected: bool | None = None
1608
+ github_indexed: bool | None = None
1609
+ demo_created: bool | None = None
1610
+ session_recording: bool | None = None
1611
+ team_created: bool | None = None
1612
+ prompt_pasted: bool | None = None
1613
+ onboarding_complete: bool | None = None
1614
+
1615
+
1616
+ @app.get("/v1/onboarding/state", response_model=OnboardingStateResponse)
1617
+ async def get_onboarding_state(team: dict = Depends(get_current_team)):
1618
+ """Return the team's onboarding progress."""
1619
+ return {"onboarding": _get_onboarding_state(team["team_id"])}
1620
+
1621
+
1622
+ @app.patch("/v1/onboarding/state", response_model=OnboardingStateResponse)
1623
+ async def patch_onboarding_state(body: OnboardingStatePatchRequest,
1624
+ team: dict = Depends(get_current_team)):
1625
+ """Merge provided onboarding fields into the team's state."""
1626
+ updates = {k: v for k, v in body.model_dump().items() if v is not None}
1627
+ state = _update_onboarding_state(team["team_id"], **updates)
1628
+ return {"onboarding": state}
1629
+
1630
+
1631
+ @app.post("/v1/onboarding/session-recording", response_model=OnboardingStateResponse)
1632
+ async def set_session_recording(body: dict, team: dict = Depends(get_current_team)):
1633
+ """Toggle automatic session recording (Q3)."""
1634
+ enabled = body.get("enabled")
1635
+ if not isinstance(enabled, bool):
1636
+ raise HTTPException(status_code=400, detail="'enabled' must be a boolean")
1637
+ state = _update_onboarding_state(team["team_id"], session_recording=enabled)
1638
+ _track_onboarding_event(team, "question_answered",
1639
+ question_id="session_recording",
1640
+ answer="yes" if enabled else "no")
1641
+ return {"onboarding": state}
1642
+
1643
+
1644
+ @app.post("/v1/onboarding/team")
1645
+ async def create_onboarding_team(body: dict, team: dict = Depends(get_current_team)):
1646
+ """Create a sub-team for the user (Q5 hosted equivalent of tortoise_team_create)."""
1647
+ name = (body.get("name") or "").strip()
1648
+ if not name or len(name) > 64:
1649
+ raise HTTPException(status_code=400, detail="name is required (max 64 chars)")
1650
+ import re
1651
+ if not re.match(r"^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$", name):
1652
+ raise HTTPException(status_code=400, detail="Invalid team name")
1653
+ sdk = _make_sdk(namespace=team["team_id"])
1654
+ try:
1655
+ result = sdk.team_create(name)
1656
+ except Exception as e:
1657
+ raise HTTPException(status_code=400, detail=f"Team create failed: {e}")
1658
+ _update_onboarding_state(team["team_id"], team_created=True)
1659
+ _track_onboarding_event(team, "question_answered",
1660
+ question_id="create_team", answer="yes")
1661
+ return {"team_id": result.get("id"), "name": name,
1662
+ "graph_name": result.get("graph_name")}
1663
+
1664
+
1665
+ @app.post("/v1/demo")
1666
+ async def public_demo(team: dict = Depends(get_current_team)):
1667
+ """Public demo graph creation (Q4) — auth-gated, team-isolated.
1668
+
1669
+ Reuses the same seeding logic as /internal/demo but requires a Bearer
1670
+ tt_ key instead of the internal key. Idempotent (sentinel check).
1671
+ """
1672
+ sdk = _make_sdk(namespace=team["team_id"])
1673
+ proj = sdk._get_proj()
1674
+ existing = proj.g.query(
1675
+ "MATCH (p:Point {id: '_demo_sentinel'}) RETURN p.id"
1676
+ ).result_set
1677
+ if existing:
1678
+ _update_onboarding_state(team["team_id"], demo_created=True)
1679
+ _track_onboarding_event(team, "first_memory_created",
1680
+ source="demo", point_count=15)
1681
+ return {"status": "already_seeded", "team_id": team["team_id"]}
1682
+
1683
+ # Call the shared demo seeder (extracted from /internal/demo)
1684
+ created = _seed_demo_graph(team["team_id"])
1685
+ _update_onboarding_state(team["team_id"], demo_created=True)
1686
+ return {"status": "seeded", "team_id": team["team_id"],
1687
+ "points_created": created}
1688
+
1689
+
1690
+ # ── Analytics instrumentation (#501) ────────────────────────────
1691
+
1692
+ # Allowed property keys for analytics events — PII-free guarantee (#501).
1693
+ # Server-side validation: unknown keys are stripped, never forwarded.
1694
+ _ALLOWED_ANALYTICS_PROPS = {
1695
+ "method", "elapsed_from_signup_s", "harness", "section",
1696
+ "elapsed_from_copy_s", "question_id", "answer", "source", "point_count",
1697
+ "session_id", "message_count", "elapsed_time_s", "steps_completed",
1698
+ "questions", "step", "error_type",
1699
+ }
1700
+
1701
+ _ANALYTICS_FALLBACK_PATH = None
1702
+
1703
+
1704
+ def _track_analytics_event(team_id: str, event_name: str,
1705
+ properties: dict | None = None) -> None:
1706
+ """Record a funnel event. PII-free; graceful when Supabase is unconfigured.
1707
+
1708
+ Writes to Supabase analytics_events when SUPABASE_URL + SUPABASE_SERVICE_KEY
1709
+ are set; otherwise appends to a local JSONL fallback. Never raises — the
1710
+ onboarding flow must not break because analytics failed.
1711
+ """
1712
+ props = {k: v for k, v in (properties or {}).items()
1713
+ if k in _ALLOWED_ANALYTICS_PROPS}
1714
+ event = {
1715
+ "team_id": team_id,
1716
+ "event_name": event_name,
1717
+ "properties": props,
1718
+ "created_at": datetime.now(timezone.utc).isoformat(),
1719
+ }
1720
+ url = os.environ.get("SUPABASE_URL")
1721
+ key = os.environ.get("SUPABASE_SERVICE_KEY")
1722
+ if url and key:
1723
+ try:
1724
+ import httpx
1725
+ with httpx.Client(timeout=5) as client:
1726
+ client.post(
1727
+ f"{url}/rest/v1/analytics_events",
1728
+ json=event,
1729
+ headers={"apikey": key, "Authorization": f"Bearer {key}",
1730
+ "Content-Type": "application/json",
1731
+ "Prefer": "return=minimal"},
1732
+ )
1733
+ return
1734
+ except Exception:
1735
+ pass # fall through to JSONL
1736
+ # JSONL fallback (~/.tortoise/analytics_fallback.jsonl)
1737
+ global _ANALYTICS_FALLBACK_PATH
1738
+ if _ANALYTICS_FALLBACK_PATH is None:
1739
+ fallback_dir = os.path.join(os.path.expanduser("~"), ".tortoise")
1740
+ os.makedirs(fallback_dir, exist_ok=True)
1741
+ _ANALYTICS_FALLBACK_PATH = os.path.join(fallback_dir, "analytics_fallback.jsonl")
1742
+ try:
1743
+ import json as _json
1744
+ with open(_ANALYTICS_FALLBACK_PATH, "a") as f:
1745
+ f.write(_json.dumps(event) + "\n")
1746
+ except Exception:
1747
+ pass
1748
+
1749
+
1750
+ def _track_onboarding_event(team: dict, event_name: str, **props) -> None:
1751
+ """Convenience: track with the current team, swallowing errors."""
1752
+ try:
1753
+ _track_analytics_event(team["team_id"], event_name, props or None)
1754
+ except Exception:
1755
+ pass
1756
+
1757
+
1758
+ # ── GitHub OAuth onboarding (#499) ──────────────────────────────
1759
+
1760
+ _GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize"
1761
+ _GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token"
1762
+ _GITHUB_API = "https://api.github.com"
1763
+ _GITHUB_STATE_TTL_S = 600 # 10 min
1764
+ _GITHUB_STATES = {} # state -> {team_id, org, created_at}
1765
+ # NOTE (P1): in-memory — single-worker only (hosted_api runs 1 uvicorn worker
1766
+ # on Fly, consistent with the auth cache, rate limiter, and _INDEX_JOBS).
1767
+ # Multi-worker would need a shared store (Redis/FalkorDB) for CSRF state.
1768
+
1769
+
1770
+ class GitHubConnectRequest(BaseModel):
1771
+ org: str | None = None
1772
+
1773
+
1774
+ @app.post("/v1/onboarding/github/connect")
1775
+ async def github_connect(body: GitHubConnectRequest | None = None,
1776
+ team: dict = Depends(get_current_team)):
1777
+ """Initiate GitHub OAuth. Returns the authorize URL + CSRF state."""
1778
+ import secrets
1779
+ from urllib.parse import urlencode
1780
+ client_id = os.environ.get("GITHUB_CLIENT_ID")
1781
+ if not client_id:
1782
+ raise HTTPException(status_code=503, detail="GitHub OAuth not configured")
1783
+ org = (body.org if body else None) or team["team_id"]
1784
+ state = secrets.token_urlsafe(24)
1785
+ _GITHUB_STATES[state] = {
1786
+ "team_id": team["team_id"],
1787
+ "org": org,
1788
+ "created_at": time.time(),
1789
+ }
1790
+ callback = os.environ.get("GITHUB_CALLBACK_URL",
1791
+ "https://api.premiselabs.co/v1/onboarding/github/callback")
1792
+ params = {
1793
+ "client_id": client_id,
1794
+ "redirect_uri": callback,
1795
+ "scope": "repo",
1796
+ "state": state,
1797
+ }
1798
+ auth_url = f"{_GITHUB_AUTHORIZE_URL}?{urlencode(params)}"
1799
+ return {"auth_url": auth_url, "state": state}
1800
+
1801
+
1802
+ @app.get("/v1/onboarding/github/callback")
1803
+ async def github_callback(code: str | None = None, state: str | None = None,
1804
+ error: str | None = None):
1805
+ """GitHub OAuth callback — exchange code, store encrypted token, redirect.
1806
+
1807
+ `error` is the standard OAuth denial query param. (Note: tests must use
1808
+ follow_redirects=False — the 302 target is the external welcome page.)
1809
+ """
1810
+ welcome_url = "https://tortoise.premiselabs.co/welcome.html"
1811
+
1812
+ if error:
1813
+ _track_analytics_event("", "onboarding_error",
1814
+ {"step": "github_connect", "error_type": "oauth_denied"})
1815
+ return RedirectResponse(f"{welcome_url}?github=denied", status_code=302)
1816
+
1817
+ # Validate state — 404 on missing/invalid (don't leak existence)
1818
+ st = _GITHUB_STATES.pop(state, None) if state else None
1819
+ if not st:
1820
+ raise HTTPException(status_code=404, detail="Not found")
1821
+ if time.time() - st["created_at"] > _GITHUB_STATE_TTL_S:
1822
+ raise HTTPException(status_code=404, detail="Not found")
1823
+ if not code:
1824
+ raise HTTPException(status_code=404, detail="Not found")
1825
+
1826
+ client_id = os.environ.get("GITHUB_CLIENT_ID")
1827
+ client_secret = os.environ.get("GITHUB_CLIENT_SECRET")
1828
+ if not client_id or not client_secret:
1829
+ raise HTTPException(status_code=503, detail="GitHub OAuth not configured")
1830
+
1831
+ # Exchange code for token
1832
+ try:
1833
+ import httpx
1834
+ async with httpx.AsyncClient(timeout=15) as client:
1835
+ r = await client.post(_GITHUB_TOKEN_URL, data={
1836
+ "client_id": client_id, "client_secret": client_secret,
1837
+ "code": code,
1838
+ }, headers={"Accept": "application/json"})
1839
+ tok = r.json()
1840
+ except Exception as e:
1841
+ raise HTTPException(status_code=502, detail=f"GitHub token exchange failed: {e}")
1842
+ access_token = tok.get("access_token")
1843
+ if not access_token:
1844
+ raise HTTPException(status_code=502, detail="GitHub token exchange failed")
1845
+
1846
+ # Encrypt + store on Team node (never log the raw token)
1847
+ from tortoise.crypto import encrypt_token
1848
+ encrypted = encrypt_token(access_token)
1849
+ team_id = st["team_id"]
1850
+ sdk = _make_sdk(namespace="registry")
1851
+ sdk._get_registry().query(
1852
+ "MATCH (t:Team {id: $id}) SET t.github_token_enc = $tok, t.github_org = $org",
1853
+ params={"id": team_id, "tok": encrypted, "org": st["org"]},
1854
+ )
1855
+ _update_onboarding_state(team_id, github_connected=True)
1856
+ _track_analytics_event(team_id, "question_answered",
1857
+ {"question_id": "github_connect", "answer": "yes"})
1858
+ return RedirectResponse(f"{welcome_url}?github=connected", status_code=302)
1859
+
1860
+
1861
+ @app.get("/v1/onboarding/github/status")
1862
+ async def github_status(team: dict = Depends(get_current_team)):
1863
+ """Return GitHub connection status + repo count."""
1864
+ sdk = _make_sdk(namespace="registry")
1865
+ rows = sdk._get_registry().query(
1866
+ "MATCH (t:Team {id: $id}) RETURN t.github_token_enc, t.github_org",
1867
+ params={"id": team["team_id"]},
1868
+ ).result_set
1869
+ if not rows or not rows[0][0]:
1870
+ return {"connected": False, "org": None, "repos_count": None}
1871
+ encrypted, org = rows[0]
1872
+ from tortoise.crypto import decrypt_token
1873
+ try:
1874
+ token = decrypt_token(encrypted)
1875
+ except ValueError:
1876
+ return {"connected": False, "org": None, "repos_count": None}
1877
+ repos_count = None
1878
+ try:
1879
+ import httpx
1880
+ with httpx.Client(timeout=10) as client:
1881
+ r = client.get(f"{_GITHUB_API}/user/repos?per_page=1",
1882
+ headers={"Authorization": f"Bearer {token}",
1883
+ "Accept": "application/vnd.github+json"})
1884
+ if r.status_code == 200:
1885
+ import re
1886
+ link = r.headers.get("Link", "")
1887
+ m = re.search(r'page=(\d+)>; rel="last"', link)
1888
+ repos_count = int(m.group(1)) if m else len(r.json())
1889
+ except Exception:
1890
+ repos_count = None
1891
+ return {"connected": True, "org": org, "repos_count": repos_count}
1892
+
1893
+
1894
+
1895
+ # ── GitHub indexing endpoints (#499 Task 5) ─────────────────────
1896
+
1897
+ _INDEX_JOBS: dict[str, dict] = {} # job_id -> {status, progress, points_created, error, created_at}
1898
+
1899
+
1900
+ class GitHubIndexRequest(BaseModel):
1901
+ org: str
1902
+ repo: str | None = None
1903
+
1904
+
1905
+ async def _run_indexing(job_id: str, team_id: str, org: str, repo: str | None) -> None:
1906
+ """Background indexing job: fetch GitHub issues/PRs → Points."""
1907
+ from tortoise.indexer.github_indexer import GitHubIndexer
1908
+ sdk = _make_sdk(namespace="registry")
1909
+ rows = sdk._get_registry().query(
1910
+ "MATCH (t:Team {id: $id}) RETURN t.github_token_enc",
1911
+ params={"id": team_id}).result_set
1912
+ if not rows or not rows[0][0]:
1913
+ _INDEX_JOBS[job_id].update({"status": "failed", "error": "GitHub not connected"})
1914
+ return
1915
+ from tortoise.crypto import decrypt_token
1916
+ try:
1917
+ token = decrypt_token(rows[0][0])
1918
+ except ValueError:
1919
+ _INDEX_JOBS[job_id].update({"status": "failed", "error": "Token undecryptable"})
1920
+ return
1921
+ try:
1922
+ team_sdk = _make_sdk(namespace=team_id)
1923
+ indexer = GitHubIndexer(token)
1924
+ result = await indexer.index_issues(team_sdk, org, repo)
1925
+ _INDEX_JOBS[job_id].update({
1926
+ "status": "completed",
1927
+ "progress": 100,
1928
+ "points_created": result["points_created"],
1929
+ "repos_processed": result["repos_processed"],
1930
+ "error": None,
1931
+ })
1932
+ _update_onboarding_state(team_id, github_indexed=True)
1933
+ except Exception as e: # noqa: BLE001
1934
+ _INDEX_JOBS[job_id].update({"status": "failed", "error": str(e)})
1935
+ finally:
1936
+ # Evict after 1 hour
1937
+ import asyncio as _asyncio
1938
+ _asyncio.get_running_loop().call_later(
1939
+ 3600, lambda: _INDEX_JOBS.pop(job_id, None))
1940
+
1941
+
1942
+ @app.post("/v1/index/github")
1943
+ async def index_github(body: GitHubIndexRequest, team: dict = Depends(get_current_team)):
1944
+ """Start a background GitHub indexing job (Q2). Returns job_id for polling."""
1945
+ import secrets
1946
+ org = (body.org or "").strip()
1947
+ if not org:
1948
+ raise HTTPException(status_code=400, detail="org is required")
1949
+ # Verify GitHub connected first
1950
+ sdk = _make_sdk(namespace="registry")
1951
+ rows = sdk._get_registry().query(
1952
+ "MATCH (t:Team {id: $id}) RETURN t.github_token_enc",
1953
+ params={"id": team["team_id"]}).result_set
1954
+ if not rows or not rows[0][0]:
1955
+ raise HTTPException(status_code=400, detail="GitHub not connected. Run connect first.")
1956
+ job_id = secrets.token_hex(8)
1957
+ _INDEX_JOBS[job_id] = {"status": "started", "progress": 0,
1958
+ "points_created": 0, "error": None,
1959
+ "team_id": team["team_id"], "created_at": time.time()}
1960
+ import asyncio as _asyncio
1961
+ _asyncio.get_event_loop().create_task(
1962
+ _run_indexing(job_id, team["team_id"], org, body.repo))
1963
+ return {"job_id": job_id, "status": "started"}
1964
+
1965
+
1966
+ @app.get("/v1/index/github/{job_id}")
1967
+ async def index_job_status(job_id: str, team: dict = Depends(get_current_team)):
1968
+ """Poll an indexing job's progress."""
1969
+ job = _INDEX_JOBS.get(job_id)
1970
+ if not job:
1971
+ raise HTTPException(status_code=404, detail="Job not found")
1972
+ # Cross-tenant isolation (P2 review fix): only the owning team can poll
1973
+ if job.get("team_id") != team["team_id"]:
1974
+ raise HTTPException(status_code=404, detail="Job not found")
1975
+ return {"job_id": job_id, **job}
1976
+
1977
+
1978
+ # ── MCP mount (#236) ─────────────────────────────────────────────
1979
+ # Mount AFTER all route definitions. DO NOT add /mcp to the parent
1980
+ # RateLimitMiddleware.SKIP — Starlette's mount already routes /mcp
1981
+ # requests to the sub-app before parent middleware runs.
1982
+ app.mount("/mcp", mcp_http_app)