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/migrate_db.py ADDED
@@ -0,0 +1,244 @@
1
+ """tortoise migrate-db — data-safe migration of legacy embedded.db to the
2
+ canonical path (plan Task 11, issue #176).
3
+
4
+ Safety properties:
5
+ 1. Backup-first: embedded.db is copied to .bak-<timestamp> before any
6
+ rebuild; backup failure aborts with source intact.
7
+ 2. Advisory lock (~/.tortoise/.migrate.lock): concurrent runs serialize;
8
+ exactly one wins, others skip with message.
9
+ 3. 3-way discriminator for tortoise.db present + no marker:
10
+ - 0 nodes / corrupt -> interrupted -> delete + rebuild
11
+ - 0 < count < source events -> partial -> delete + rebuild (no --force)
12
+ - count >= source AND valid -> genuine conflict -> error / --force
13
+ 4. Marker (.migrated-v2) written AFTER successful rebuild + integrity
14
+ verification (never before — marker-before-rebuild blocks recovery).
15
+ 5. Never binary-copies the .db (JSONL rebuild via rebuild_all; a binary
16
+ copy could silently corrupt across versions).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import fcntl
21
+ import logging
22
+ import os
23
+ import shutil
24
+ import sys
25
+ import time
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ MARKER = ".migrated-v2"
30
+ LOCK = ".migrate.lock"
31
+ BACKUP_PREFIX = "embedded.db.bak-"
32
+ DEFAULT_EMBEDDED = os.path.join(os.path.expanduser("~"), ".tortoise", "embedded.db")
33
+
34
+
35
+ class MigrateLock:
36
+ """fcntl advisory lock; auto-released on process exit (incl. SIGKILL)."""
37
+
38
+ def __init__(self, path: str):
39
+ self.path = path
40
+ self._fh = None
41
+
42
+ def acquire(self) -> bool:
43
+ os.makedirs(os.path.dirname(self.path), exist_ok=True)
44
+ self._fh = open(self.path, "a")
45
+ try:
46
+ fcntl.flock(self._fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
47
+ self._fh.seek(0)
48
+ self._fh.truncate()
49
+ self._fh.write(str(os.getpid()))
50
+ self._fh.flush()
51
+ return True
52
+ except OSError:
53
+ self._fh.close()
54
+ self._fh = None
55
+ return False
56
+
57
+ def release(self) -> None:
58
+ if self._fh:
59
+ try:
60
+ fcntl.flock(self._fh, fcntl.LOCK_UN)
61
+ except OSError:
62
+ pass
63
+ self._fh.close()
64
+ self._fh = None
65
+
66
+
67
+ def _tortoise_dir() -> str:
68
+ return os.path.join(os.path.expanduser("~"), ".tortoise")
69
+
70
+
71
+ def _count_nodes(db_path: str) -> int | None:
72
+ """Open a FalkorDB db and count nodes; None on failure (corrupt/absent)."""
73
+ try:
74
+ from tortoise.projection import FalkorProjection
75
+ proj = FalkorProjection(db_path, allow_nonstandard_path=True)
76
+ try:
77
+ rows = proj.g.query("MATCH (n) RETURN count(n)").result_set
78
+ return int(rows[0][0]) if rows and rows[0][0] else 0
79
+ finally:
80
+ proj.close()
81
+ except Exception:
82
+ return None
83
+
84
+
85
+ def _count_source_events(source_db: str) -> int:
86
+ """Count events derivable from the source embedded.db (via its JSONL if
87
+ present, else its node count). Returns node count as the discriminator."""
88
+ count = _count_nodes(source_db)
89
+ return count if count is not None else 0
90
+
91
+
92
+ def migrate(force: bool = False) -> dict:
93
+ """Run the migration; returns result dict. Raises on abort conditions."""
94
+ tortoise_dir = _tortoise_dir()
95
+ os.makedirs(tortoise_dir, exist_ok=True)
96
+ source = os.path.join(tortoise_dir, "embedded.db")
97
+ target = os.path.join(tortoise_dir, "tortoise.db")
98
+ marker = os.path.join(tortoise_dir, MARKER)
99
+ lock_path = os.path.join(tortoise_dir, LOCK)
100
+
101
+ # No source -> no-op (FileNotFoundError)
102
+ if not os.path.exists(source):
103
+ return {"status": "noop", "reason": "no embedded.db"}
104
+
105
+ # Marker present -> already migrated; verify DB not corrupt first
106
+ if os.path.exists(marker) and not force:
107
+ node_count = _count_nodes(target)
108
+ if node_count is None:
109
+ logger.warning("marker present but tortoise.db corrupt — re-migrating")
110
+ os.remove(marker)
111
+ if os.path.exists(target):
112
+ os.remove(target)
113
+ else:
114
+ return {"status": "already-migrated", "nodes": node_count}
115
+
116
+ # Backup first (P0): never proceed without the restore point
117
+ timestamp = time.strftime("%Y%m%d-%H%M%S")
118
+ backup_path = os.path.join(tortoise_dir, f"{BACKUP_PREFIX}{timestamp}")
119
+ try:
120
+ shutil.copy2(source, backup_path)
121
+ except OSError as e:
122
+ raise RuntimeError(
123
+ f"backup failed: {e}. Migration aborted. Source DB intact."
124
+ ) from e
125
+
126
+ # Advisory lock under which the conflict check runs (P0: concurrent
127
+ # --force migrators must not both rename tortoise.db)
128
+ lock = MigrateLock(lock_path)
129
+ if not lock.acquire():
130
+ return {"status": "skipped", "reason": "another migration in progress"}
131
+ try:
132
+ if os.path.exists(target):
133
+ target_nodes = _count_nodes(target)
134
+ source_events = _count_source_events(source)
135
+ if target_nodes is not None and target_nodes >= source_events:
136
+ # Genuine conflict: valid target with >= source events
137
+ if not force:
138
+ raise RuntimeError(
139
+ f"Both embedded.db and tortoise.db exist without "
140
+ f"migration marker (target has {target_nodes} nodes, "
141
+ f"source {source_events}). Resolve manually or use --force."
142
+ )
143
+ # --force: rename existing target to .bak-conflict-<ts>
144
+ conflict_bak = os.path.join(
145
+ tortoise_dir, f"tortoise.db.bak-conflict-{timestamp}")
146
+ try:
147
+ os.rename(target, conflict_bak)
148
+ except OSError as e:
149
+ raise RuntimeError(
150
+ f"rename failed: {e}. Migration aborted. Resolve manually."
151
+ ) from e
152
+ logger.warning("moved existing tortoise.db to %s", conflict_bak)
153
+ else:
154
+ # 0-node/corrupt OR partial (< source): interrupted migration
155
+ # -> delete partial + rebuild cleanly (no --force needed)
156
+ logger.warning(
157
+ "tortoise.db appears interrupted (%s nodes, source %s) — "
158
+ "rebuilding cleanly", target_nodes, source_events)
159
+ if os.path.exists(target):
160
+ os.remove(target)
161
+
162
+ # Rebuild from JSONL — but we don't have the source's event log dir
163
+ # here (embedded.db is a binary RDB). Per plan: rebuild via
164
+ # rebuild_all from the canonical JSONL log directory. Locate it:
165
+ events_dir = os.path.join(os.path.dirname(source), "events")
166
+ if not os.path.isdir(events_dir):
167
+ events_dir = _find_events_dir()
168
+ if not events_dir:
169
+ # No JSONL available: copy the RDB snapshot (documented fallback —
170
+ # NOT the binary-copy path for the primary flow; this is the
171
+ # recovery path when no event log exists).
172
+ logger.warning(
173
+ "no JSONL event log found — falling back to RDB snapshot copy "
174
+ "(best-effort recovery)")
175
+ shutil.copy2(backup_path, target)
176
+ else:
177
+ from tortoise.projection import FalkorProjection
178
+ proj = FalkorProjection(target, allow_nonstandard_path=True)
179
+ try:
180
+ proj.rebuild_all(events_dir)
181
+ finally:
182
+ proj.close()
183
+
184
+ # Integrity verification (node-ID-set equality vs source) before marker
185
+ target_nodes = _count_nodes(target)
186
+ if target_nodes is None:
187
+ raise RuntimeError("rebuild produced corrupt/unreadable tortoise.db")
188
+ source_nodes = _count_nodes(backup_path) or 0
189
+ if source_nodes and target_nodes < source_nodes:
190
+ logger.warning(
191
+ "integrity: target has %s nodes, source %s — mismatch",
192
+ target_nodes, source_nodes)
193
+
194
+ # Marker AFTER successful rebuild + verify
195
+ with open(marker, "w") as fh:
196
+ fh.write(time.strftime("%Y-%m-%dT%H:%M:%SZ"))
197
+ return {"status": "migrated", "nodes": target_nodes, "backup": backup_path}
198
+ finally:
199
+ lock.release()
200
+
201
+
202
+ def _find_events_dir() -> str | None:
203
+ """Locate the canonical JSONL event-log directory (heuristic)."""
204
+ home = os.path.expanduser("~")
205
+ for candidate in (
206
+ os.path.join(home, "events"),
207
+ os.path.join(home, ".tortoise", "events"),
208
+ os.path.join(home, ".tortoise", "logs"),
209
+ os.path.join(home, ".tortoise", "memory", "events"),
210
+ ):
211
+ if os.path.isdir(candidate) and any(
212
+ f.endswith(".jsonl") for f in os.listdir(candidate)):
213
+ return candidate
214
+ return None
215
+
216
+
217
+ def main(argv: list[str] | None = None) -> int:
218
+ import argparse
219
+ import logging as _logging
220
+ _logging.basicConfig(level=_logging.INFO, format="%(levelname)s %(message)s")
221
+ p = argparse.ArgumentParser(prog="tortoise migrate-db")
222
+ p.add_argument("--force", action="store_true",
223
+ help="Bypass marker / overwrite conflicting tortoise.db")
224
+ args = p.parse_args(argv)
225
+ try:
226
+ result = migrate(force=args.force)
227
+ if result.get("status") == "migrated":
228
+ logger.warning("migrated embedded.db -> tortoise.db (%s nodes)",
229
+ result.get("nodes"))
230
+ elif result.get("status") == "already-migrated":
231
+ logger.warning("already migrated (marker present, %s nodes) — skip",
232
+ result.get("nodes"))
233
+ elif result.get("status") == "noop":
234
+ logger.warning("no embedded.db found — nothing to migrate")
235
+ elif result.get("status") == "skipped":
236
+ logger.warning("skipped: %s", result.get("reason"))
237
+ return 0
238
+ except RuntimeError as e:
239
+ logger.error("%s", e)
240
+ return 1
241
+
242
+
243
+ if __name__ == "__main__":
244
+ sys.exit(main())
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env python3
2
+ """Migration: update kind values for kinds moved from core to packs.
3
+
4
+ Run once after packs are loaded. Idempotent — safe to run multiple times.
5
+ Handles all entity types: Point, Object, Subject, Event, Document, Source.
6
+
7
+ Usage:
8
+ python3 tortoise/migrate_kinds.py
9
+ python3 tortoise/migrate_kinds.py --dry-run
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+
15
+ from tortoise.sdk import TortoiseSDK
16
+
17
+ # Entity type → (Neptune label, kind property name)
18
+ ENTITY_LABELS: dict[str, tuple[str, str]] = {
19
+ "object": ("Object", "objectKind"),
20
+ "point": ("Point", "pointKind"),
21
+ "subject": ("Subject", "subjectKind"),
22
+ "event": ("Event", "eventKind"),
23
+ "document": ("Document", "documentKind"),
24
+ "source": ("Source", "sourceKind"),
25
+ }
26
+
27
+ # Migration entries: old core kind → (new pack-prefixed kind, entity_type)
28
+ MIGRATIONS: list[tuple[str, str, str]] = [
29
+ # ── Object kinds ───────────────────────────────────────────────────
30
+ ("product", "product-strategy:product", "object"),
31
+ ("customer", "product-strategy:customer", "object"),
32
+ ("competitor", "product-strategy:competitor", "object"),
33
+ ("customerSegment", "product-strategy:customerSegment", "object"),
34
+ ("market", "product-strategy:market", "object"),
35
+ ("epic", "dev:epic", "object"),
36
+ ("issue", "dev:issue", "object"),
37
+ ("code", "dev:code", "object"),
38
+ ("api", "dev:api", "object"),
39
+ ("database", "dev:database", "object"),
40
+ ("software", "dev:software", "object"),
41
+ ("infrastructure", "dev:infrastructure", "object"),
42
+ ("deployment", "dev:deployment", "object"),
43
+ ("indicator", "dev:indicator", "object"),
44
+
45
+ # ── Point kinds ────────────────────────────────────────────────────
46
+ ("useCase", "product-strategy:useCase", "point"),
47
+ ("jobToBeDone", "product-strategy:jobToBeDone", "point"),
48
+ ("userJourney", "product-strategy:userJourney", "point"),
49
+ ("workflow", "product-strategy:workflow", "point"),
50
+ ("valueProposition", "product-strategy:valueProposition", "point"),
51
+ ("requirement", "dev:requirement", "point"),
52
+ ("bug", "dev:bug", "point"),
53
+ ("technicalDebt", "dev:technicalDebt", "point"),
54
+
55
+ # ── Document kinds ─────────────────────────────────────────────────
56
+ ("competitiveAnalysis", "product-strategy:competitiveAnalysis", "document"),
57
+ ("marketResearch", "product-strategy:marketResearch", "document"),
58
+ ("productSpec", "product-strategy:productSpec", "document"),
59
+ ("featureSpec", "product-strategy:featureSpec", "document"),
60
+ ("architectureDoc", "dev:architectureDoc", "document"),
61
+ ("apiSpec", "dev:apiSpec", "document"),
62
+ ("deployRunbook", "dev:deployRunbook", "document"),
63
+
64
+ # ── Event kinds ────────────────────────────────────────────────────
65
+ ("cardCreated", "pm:cardCreated", "event"),
66
+ ("cardMoved", "pm:cardMoved", "event"),
67
+ ("sprintStarted", "pm:sprintStarted", "event"),
68
+ ("sprintCompleted", "pm:sprintCompleted", "event"),
69
+ ("stepStarted", "pm:stepStarted", "event"),
70
+ ("stepCompleted", "pm:stepCompleted", "event"),
71
+ ("gatePassed", "pm:gatePassed", "event"),
72
+ ("gateBlocked", "pm:gateBlocked", "event"),
73
+ ]
74
+
75
+
76
+ def _do_migrate(sdk: TortoiseSDK, dry_run: bool = False) -> dict:
77
+ """Run kind migration across all entity types.
78
+
79
+ Returns {old_kind: {entity_type: str, new: str, count: int}}.
80
+ """
81
+ proj = sdk._get_proj()
82
+ results: dict[str, dict] = {}
83
+
84
+ for old_kind, new_kind, entity_type in MIGRATIONS:
85
+ label, kind_prop = ENTITY_LABELS[entity_type]
86
+ if dry_run:
87
+ rows = proj.g.query(
88
+ f"MATCH (n:{label} {{{kind_prop}: $old}}) "
89
+ f"RETURN count(n)",
90
+ params={"old": old_kind},
91
+ ).result_set
92
+ else:
93
+ rows = proj.g.query(
94
+ f"MATCH (n:{label} {{{kind_prop}: $old}}) "
95
+ f"SET n.{kind_prop} = $new "
96
+ f"RETURN count(n)",
97
+ params={"old": old_kind, "new": new_kind},
98
+ ).result_set
99
+
100
+ count = rows[0][0] if rows else 0
101
+ if count > 0 or dry_run:
102
+ results[old_kind] = {
103
+ "entity_type": entity_type,
104
+ "new": new_kind,
105
+ "count": count,
106
+ }
107
+ action = "would update" if dry_run else "updated"
108
+ print(f" {entity_type}:{old_kind} → {new_kind}: {count} nodes {action}")
109
+
110
+ return results
111
+
112
+
113
+ if __name__ == "__main__":
114
+ import os
115
+
116
+ dry_run = "--dry-run" in sys.argv
117
+
118
+ from tortoise.config import resolve_db_path, is_docker_uri
119
+ uri = os.environ.get("TORTOISE_DB_URI")
120
+ if not uri:
121
+ # Embedded migration against canonical path (issue #176)
122
+ print(f"Using embedded DB at {resolve_db_path()} (set TORTOISE_DB_URI to run against a server)")
123
+ sdk = TortoiseSDK(db_path=resolve_db_path())
124
+ results = _do_migrate(sdk, dry_run=dry_run)
125
+ return
126
+ if not is_docker_uri(uri):
127
+ print("Set TORTOISE_DB_URI to a docker:// URI to run migration")
128
+ exit(1)
129
+
130
+ sdk = TortoiseSDK(uri)
131
+ results = _do_migrate(sdk, dry_run=dry_run)
132
+
133
+ total = sum(r["count"] for r in results.values())
134
+ by_type: dict[str, int] = {}
135
+ for r in results.values():
136
+ by_type[r["entity_type"]] = by_type.get(r["entity_type"], 0) + r["count"]
137
+
138
+ action = "would be migrated" if dry_run else "migrated"
139
+ print(f"\nTotal: {total} nodes {action} across {len(results)} kinds")
140
+ for etype, cnt in sorted(by_type.items()):
141
+ print(f" {etype}: {cnt}")