tortoise-graph 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,142 @@
1
+ """Domain loader — extensible kind registry and routing for domain ontologies.
2
+
3
+ The base vocabulary lives here (mirrors ONTOLOGY §12). Domain ontologies
4
+ (Product Strategy, custom user ontologies) register additional kind values
5
+ via ``register_kind()``. The system accepts any string — the registry is
6
+ descriptive (used for warnings), not restrictive.
7
+
8
+ Domain manifest (config/domain_manifest.yaml) provides routing configuration:
9
+ query patterns, event types, Cypher templates, timeout, priority.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ # Base known kinds (ONTOLOGY §12).
18
+ _BASE_KINDS: set[str] = {
19
+ "statement", "decision", "vision", "strategy",
20
+ "plan", "goal", "target", "observation", "hypothesis",
21
+ "jobToBeDone", "useCase", "userJourney", "workflow", "requirement", "issue",
22
+ # Event kinds
23
+ "session", "meeting", "milestone", "incident",
24
+ # #531: human approval — event kind + decision point kind (approval pattern)
25
+ "humanApproval",
26
+ }
27
+
28
+
29
+ def known_kinds() -> set[str]:
30
+ """Return the current set of known kind values (base + registered)."""
31
+ return frozenset(_BASE_KINDS) # ponytail: frozen to avoid accidental mutation
32
+
33
+
34
+ def register_kind(kind: str) -> None:
35
+ """Register an additional kind value from a domain ontology."""
36
+ _BASE_KINDS.add(kind)
37
+
38
+
39
+ def kind_is_known(kind: str) -> bool:
40
+ """Check if a kind value is in the known registry."""
41
+ return kind in _BASE_KINDS
42
+
43
+
44
+ # ── Domain Routing Config ─────────────────────────────
45
+
46
+ @dataclass
47
+ class DomainRoutingConfig:
48
+ """Routing configuration for one domain ontology."""
49
+ key: str
50
+ name: str
51
+ active: bool = True
52
+ version: str = "1.0"
53
+ event_types: list[str] = field(default_factory=list)
54
+ query_patterns: list[str] = field(default_factory=list)
55
+ cypher_template: str = ""
56
+ timeout: float = 5.0
57
+ priority: int = 10
58
+
59
+
60
+ def load_manifest(manifest_path: str | Path | None = None) -> dict[str, DomainRoutingConfig]:
61
+ """Parse domain manifest YAML → {domain_key: DomainRoutingConfig}.
62
+
63
+ Returns empty dict if manifest not found or YAML not installed.
64
+ """
65
+ if manifest_path is None:
66
+ manifest_path = Path(__file__).parent.parent / "config" / "domain_manifest.yaml"
67
+ else:
68
+ manifest_path = Path(manifest_path)
69
+
70
+ if not manifest_path.exists():
71
+ return {}
72
+
73
+ import yaml
74
+ with open(manifest_path) as f:
75
+ data = yaml.safe_load(f) or {}
76
+
77
+ domains: dict[str, DomainRoutingConfig] = {}
78
+ for key, raw in (data.get("domains") or {}).items():
79
+ if not raw.get("active", True):
80
+ continue
81
+ # Register kind values from manifest
82
+ kind_values = raw.get("kind_values") or {}
83
+ for kind_list in kind_values.values():
84
+ for k in kind_list:
85
+ register_kind(k)
86
+ domains[key] = DomainRoutingConfig(
87
+ key=key,
88
+ name=raw.get("name", key),
89
+ active=True,
90
+ version=raw.get("version", "1.0"),
91
+ event_types=raw.get("event_types") or [],
92
+ query_patterns=raw.get("query_patterns") or [],
93
+ cypher_template=raw.get("cypher_template") or "",
94
+ timeout=float(raw.get("timeout", 5.0)),
95
+ priority=int(raw.get("priority", 10)),
96
+ )
97
+ return domains
98
+
99
+
100
+ def domain_event_types(domains: dict[str, DomainRoutingConfig]) -> dict[str, list[str]]:
101
+ """Extract {domain_key: [event_type, ...]} for write-side routing."""
102
+ return {k: v.event_types for k, v in domains.items()}
103
+
104
+
105
+ def domain_query_patterns(domains: dict[str, DomainRoutingConfig]) -> dict[str, list[str]]:
106
+ """Extract {pattern: [domain_key, ...]} for read-side routing."""
107
+ patterns: dict[str, list[str]] = {}
108
+ for key, cfg in domains.items():
109
+ for p in cfg.query_patterns:
110
+ patterns.setdefault(p, []).append(key)
111
+ return patterns
112
+
113
+
114
+ def domain_cypher_templates(domains: dict[str, DomainRoutingConfig]) -> dict[str, str]:
115
+ """Extract {domain_key: cypher} for dispatch."""
116
+ return {k: v.cypher_template for k, v in domains.items() if v.cypher_template}
117
+
118
+
119
+ def resolve_domain_from_path(file_path: str, manifest_path: str | Path | None = None) -> str:
120
+ """Resolve domain from file path using manifest's directory_map.
121
+
122
+ Longest-prefix match wins. Falls back to "capability" for unmatched paths.
123
+ """
124
+ if manifest_path is None:
125
+ manifest_path = Path(__file__).parent.parent / "config" / "domain_manifest.yaml"
126
+ manifest_path = Path(manifest_path)
127
+
128
+ if not manifest_path.exists():
129
+ return "capability"
130
+
131
+ import yaml
132
+ with open(manifest_path) as f:
133
+ data = yaml.safe_load(f) or {}
134
+
135
+ directory_map: dict[str, str] = data.get("directory_map") or {}
136
+ # Sort by prefix length descending for longest-prefix match
137
+ sorted_prefixes = sorted(directory_map.items(), key=lambda kv: len(kv[0]), reverse=True)
138
+ for prefix, domain in sorted_prefixes:
139
+ if file_path.startswith(prefix):
140
+ return domain
141
+
142
+ return "capability"
tortoise/dream.py ADDED
@@ -0,0 +1,153 @@
1
+ """Dreaming — background EP stabilization for the Tortoise graph (#85).
2
+
3
+ Two-tier architecture (fast path + slow path):
4
+ Fast path: per-query impact-subgraph EP via compute_confidence(anchors=...)
5
+ Slow path: dreaming — whole-graph/incremental EP stabilization
6
+
7
+ The Dreamer reuses the landed fast-path selector (_bfs_select_operators) and
8
+ the batch-I/O EP engine (TortoiseEP). It is the Tortoise analogue of memory
9
+ consolidation / sleep consolidation: not answering a query, keeping the graph
10
+ honest after batch writes.
11
+
12
+ Design (Hybrid C, #85):
13
+ - ``dream(anchors, hops)`` — incremental: BFS from anchor points, run EP on
14
+ the affected subgraph, write back confidences.
15
+ - ``dream_all()`` — full-graph stabilization from all non-operator points.
16
+ - Async decoupling: fast-path queries never block on dreaming (dreaming is
17
+ triggered post-batch, lazy-on-read, or on-demand via SDK/MCP).
18
+
19
+ Concurrency contract (#85):
20
+ - Embedded mode: dreaming runs synchronously in-band after write batches
21
+ (no daemon thread — avoids SQLite/redislite single-writer hazards, #6761,
22
+ and the #176 process leak). Latency budget: ≤500ms on the dirty subgraph.
23
+ - Hosted mode: per-tenant async queue in hosted_api.py; cooperative asyncio
24
+ tasks (server-mode FalkorDB handles concurrency natively).
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ import threading
30
+
31
+ _log = logging.getLogger(__name__)
32
+
33
+ # Default EP subgraph expansion for incremental dreaming. _mark_dirty seeds
34
+ # 1-hop; the dream expands to max_hops for full propagation. DO NOT reduce
35
+ # below 2 without expanding _mark_dirty (contract, #85).
36
+ DEFAULT_MAX_HOPS = 2
37
+
38
+ # Embedded in-band latency budget (seconds). If a dream exceeds this, the
39
+ # caller falls back to lazy-read + the scheduled dream_all (#85).
40
+ EMBEDDED_LATENCY_BUDGET_S = 0.5
41
+
42
+
43
+ class Dreamer:
44
+ """Incremental + whole-graph EP stabilization.
45
+
46
+ Thread-safe: a lock serializes dream runs so concurrent triggers
47
+ (post-batch, lazy-read, explicit) never overlap on the same SDK.
48
+ """
49
+
50
+ def __init__(self, sdk):
51
+ self._sdk = sdk
52
+ self._lock = threading.Lock()
53
+
54
+ # ── Incremental ────────────────────────────────────────────────
55
+
56
+ def dream(self, anchors: list[str], max_hops: int = DEFAULT_MAX_HOPS,
57
+ direction: str = "both") -> dict:
58
+ """Run EP over the subgraph reachable from ``anchors``.
59
+
60
+ Reuses the fast-path selector (analyze._bfs_select_operators, capped
61
+ at 200 operators) and TortoiseEP.run with batch I/O. Returns
62
+ {iterations, converged, affected_claims}.
63
+ """
64
+ if not anchors:
65
+ return {"iterations": 0, "converged": True, "affected_claims": []}
66
+ with self._lock:
67
+ proj = self._sdk._get_proj()
68
+ from .analyze import _bfs_select_operators
69
+ operator_ids = list(_bfs_select_operators(
70
+ proj, anchors, max_hops=max_hops, rel_filter="IMPL|NAND",
71
+ direction=direction,
72
+ ))
73
+ if not operator_ids:
74
+ return {"iterations": 0, "converged": True, "affected_claims": []}
75
+ ep = self._sdk._get_ep()
76
+ # #330: dream must honour the SDK's persistent evidence (baselines)
77
+ # — hydrate graph-persisted baselines and pass a copy to ep.run.
78
+ # run() is call-scoped, so the copy cannot leak into later runs.
79
+ self._sdk._hydrate_evidence()
80
+ iterations, converged = ep.run(
81
+ operator_ids, max_hops=max_hops,
82
+ evidence=dict(self._sdk._evidence),
83
+ )
84
+ # Persist mean confidence to node property (mirrors compute_confidence).
85
+ # P2 (#85): use the SAME max_hops as the run so the affected set
86
+ # matches what _load_cache/_flush_cache covered.
87
+ affected = ep._affected_claims(operator_ids, max_hops=max_hops)
88
+ from datetime import datetime, timezone
89
+ now = datetime.now(timezone.utc).isoformat()
90
+ for claim_id in affected:
91
+ conf = ep.compute_confidence(claim_id)
92
+ proj.g.query(
93
+ "MATCH (n:Point {id:$id}) SET n.confidence = $c, n.updatedAt = $now",
94
+ params={"id": claim_id, "c": conf["mean"], "now": now},
95
+ )
96
+ return {
97
+ "iterations": iterations,
98
+ "converged": converged,
99
+ "affected_claims": sorted(affected),
100
+ }
101
+
102
+ # ── Whole-graph ────────────────────────────────────────────────
103
+
104
+ def dream_all(self, max_hops: int = 2,
105
+ batch_size: int = 2000,
106
+ max_total_operators: int = 200_000) -> dict:
107
+ """Full-graph EP stabilization from all non-operator Points.
108
+
109
+ Memory + DoS guard (#85, security P1): batches the anchor set so the
110
+ EP cache never loads the entire graph at once, AND caps the total
111
+ operators processed across batches so a single request cannot trigger
112
+ an unbounded whole-graph EP on the hosted deployment.
113
+
114
+ Returns {batches, total_affected, converged_all}.
115
+ """
116
+ proj = self._sdk._get_proj()
117
+ rows = proj.g.query(
118
+ "MATCH (n:Point) WHERE (n.is_operator IS NULL OR n.is_operator = false) "
119
+ "RETURN n.id"
120
+ ).result_set
121
+ anchors = [r[0] for r in rows]
122
+ if not anchors:
123
+ return {"batches": 0, "total_affected": 0, "converged_all": True}
124
+
125
+ total_affected: set[str] = set()
126
+ converged_all = True
127
+ batches = 0
128
+ total_operators = 0
129
+ for start in range(0, len(anchors), batch_size):
130
+ chunk = anchors[start:start + batch_size]
131
+ with self._lock:
132
+ from .analyze import _bfs_select_operators
133
+ chunk_ops = list(_bfs_select_operators(
134
+ proj, chunk, max_hops=max_hops, rel_filter="IMPL|NAND",
135
+ direction="both",
136
+ ))
137
+ total_operators += len(chunk_ops)
138
+ if total_operators > max_total_operators:
139
+ _log.warning(
140
+ "dream_all truncated at %d operators (cap %d) — "
141
+ "graph larger than budget",
142
+ total_operators, max_total_operators,
143
+ )
144
+ break
145
+ result = self.dream(chunk, max_hops=max_hops)
146
+ batches += 1
147
+ total_affected.update(result.get("affected_claims", []))
148
+ converged_all = converged_all and result.get("converged", False)
149
+ return {
150
+ "batches": batches,
151
+ "total_affected": len(total_affected),
152
+ "converged_all": converged_all,
153
+ }