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/svbp.py ADDED
@@ -0,0 +1,446 @@
1
+ # DEPRECATED: SVBP algorithm replaced by Expectation Propagation (ep.py). Kept for reference only.
2
+ """SVBP (Stein Variational Belief Propagation) for Tortoise.
3
+
4
+ Per-factor Stein updates with cavity messages. Like EP but with
5
+ SVGD particles instead of Gauss-Jacobi quadrature for the tilt step.
6
+ Handles multimodality under NAND constraints (Gate 1 confirmed camps form).
7
+
8
+ Architecture mirrors tortoise/ep.py:
9
+ Cavity: remove factor message from claim posterior
10
+ Tilt: run SVGD on cavity × factor potential
11
+ Project: fit Beta to particles → natural params → new messages
12
+ Damp: weighted average with previous message
13
+
14
+ ponytail: particles live in-memory per claim. No FalkorDB storage yet.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import jax.numpy as jnp
19
+ import jax
20
+ import jax.random as jrandom
21
+ import numpy as np
22
+
23
+
24
+ # ═══════════════════════════════════════════════════════════════════
25
+ # SVGD primitives (same as svbp_gate1.py)
26
+ # ═══════════════════════════════════════════════════════════════════
27
+
28
+ def sigmoid(x):
29
+ return 1.0 / (1.0 + jnp.exp(-x))
30
+
31
+ @jax.jit
32
+ def rbf_kernel(x, h):
33
+ n, d = x.shape
34
+ diff = x[:, None, :] - x[None, :, :]
35
+ sqdist = jnp.sum(diff ** 2, axis=-1)
36
+ K = jnp.exp(-sqdist / (2 * h * h + 1e-8))
37
+ grad_K = -K[:, :, None] * diff / (h * h + 1e-8)
38
+ return K, grad_K
39
+
40
+ @jax.jit
41
+ def median_heuristic(x):
42
+ n = x.shape[0]
43
+ diff = x[:, None, :] - x[None, :, :]
44
+ sqdist = jnp.sum(diff ** 2, axis=-1)
45
+ triu = sqdist[jnp.triu_indices(n, k=1)]
46
+ return jnp.sqrt(jnp.median(triu) / 2 + 1e-8)
47
+
48
+ @jax.jit
49
+ def svgd_update(x, grad_log_p, h):
50
+ n, d = x.shape
51
+ K, grad_K = rbf_kernel(x, h)
52
+ term1 = jnp.dot(K, grad_log_p) / n
53
+ term2 = jnp.sum(grad_K, axis=0) / n
54
+ return term1 + term2
55
+
56
+
57
+ # ═══════════════════════════════════════════════════════════════════
58
+ # Beta parameter fitting from particles
59
+ # ═══════════════════════════════════════════════════════════════════
60
+
61
+ def moments_to_beta_params(m1, m2):
62
+ """Convert E[c] and E[c²] to Beta(α, β). Min clamp at 0.01.
63
+
64
+ Guards against NaN/Inf inputs (returns uniform fallback).
65
+ """
66
+ # Guard: NaN or Inf moments → uniform fallback
67
+ if not (jnp.isfinite(m1) and jnp.isfinite(m2)):
68
+ return (1.0, 1.0)
69
+ var = max(m2 - m1 * m1, 1e-12)
70
+ if var <= 1e-12: # ponytail: near-zero variance = degenerate → uniform
71
+ return (1.0, 1.0)
72
+ if var >= m1 * (1 - m1) * 0.999:
73
+ return (1.0, 1.0) # fallback to uniform
74
+ total = m1 * (1 - m1) / var - 1
75
+ if total <= 0:
76
+ return (1.0, 1.0)
77
+ alpha = max(total * m1, 0.01)
78
+ beta = max(total * (1 - m1), 0.01)
79
+ return (float(alpha), float(beta))
80
+
81
+
82
+ # ═══════════════════════════════════════════════════════════════════
83
+ # TortoiseSVBP
84
+ # ═══════════════════════════════════════════════════════════════════
85
+
86
+ @jax.jit
87
+ def _tilt_log_prob(y_pair, cav_alpha_a, cav_beta_a, cav_alpha_b, cav_beta_b, is_nand, weight):
88
+ """Log-prob for one particle pair in tilted distribution.
89
+ All params are explicit (no closures) so JAX traces once.
90
+ """
91
+ c_a = sigmoid(y_pair[0])
92
+ c_b = sigmoid(y_pair[1])
93
+ eps = 1e-12
94
+ lp = (cav_alpha_a * jnp.log(c_a + eps) + cav_beta_a * jnp.log(1 - c_a + eps)
95
+ + cav_alpha_b * jnp.log(c_b + eps) + cav_beta_b * jnp.log(1 - c_b + eps))
96
+ # is_nand: 1.0 for NAND, 0.0 for IMPL
97
+ nand_term = -weight * c_a * c_b
98
+ impl_term = -weight * (c_a - c_b) ** 2
99
+ lp = lp + is_nand * nand_term + (1 - is_nand) * impl_term
100
+ return lp
101
+
102
+ # Batch gradient: (n,2) and scalars → (n,2)
103
+ _tilt_grad_fn = jax.grad(_tilt_log_prob) # (2,) + scalars → (2,)
104
+ _tilt_grad_batch = jax.jit(jax.vmap(_tilt_grad_fn, in_axes=(0, None, None, None, None, None, None)))
105
+
106
+ class TortoiseSVBP:
107
+ """Stein Variational Belief Propagation for Tortoise factor graphs.
108
+
109
+ Parameters:
110
+ n_particles: SVGD particles per factor update.
111
+ n_svgd_steps: SVGD iterations per factor update (inner loop).
112
+ svgd_lr: step size for per-factor SVGD.
113
+ damping: message damping factor, 0 < λ ≤ 1.
114
+ max_iter: max outer EP iterations.
115
+ tol: convergence threshold.
116
+ """
117
+
118
+ def __init__(self, *, n_particles=50, n_svgd_steps=20, svgd_lr=0.01,
119
+ damping=0.5, max_iter=50, tol=1e-3, seed=42,
120
+ compress_after=5):
121
+ self.n_particles = n_particles
122
+ self.n_svgd_steps = n_svgd_steps
123
+ self.svgd_lr = svgd_lr
124
+ self.damping = damping
125
+ if not (0 < damping <= 1):
126
+ raise ValueError(
127
+ f"damping must be in (0, 1], got {damping}. "
128
+ f"d=0 freezes messages; d>1 causes oscillatory divergence."
129
+ )
130
+ self.max_iter = max_iter
131
+ self.tol = tol
132
+ self.compress_after = compress_after
133
+ self.key = jrandom.PRNGKey(seed)
134
+
135
+ # Messages: {(op_id, claim_id, rel_type): (msg_alpha, msg_beta)}
136
+ self.messages: dict[tuple[str, str, str], tuple[float, float]] = {}
137
+ # Fixed evidence priors (never updated during message passing)
138
+ self.evidence_prior: dict[str, tuple[float, float]] = {}
139
+ # Claim posteriors: {claim_id: (alpha, beta)} = evidence + sum(messages)
140
+ self.posteriors: dict[str, tuple[float, float]] = {}
141
+ # Gate 3: particle storage + compression
142
+ self._particles: dict[str, jnp.ndarray] = {} # active particles (logit space)
143
+ self._summaries: dict[str, tuple[float, float]] = {} # Beta summaries for compressed claims
144
+ self._stale: dict[str, int] = {} # iterations since last update per claim
145
+
146
+ # ── Natural parameter helpers ─────────────────────────────────
147
+
148
+ @staticmethod
149
+ def _natural_from_beta(alpha, beta):
150
+ """Beta(α,β) → (η₁=α-1, η₂=β-1)."""
151
+ return (alpha - 1, beta - 1)
152
+
153
+ @staticmethod
154
+ def _beta_from_natural(eta1, eta2):
155
+ """Natural params → Beta. Clamp ≥ 0.01."""
156
+ return (max(eta1 + 1, 0.01), max(eta2 + 1, 0.01))
157
+
158
+ # ── Message read/write ────────────────────────────────────────
159
+
160
+ def _get_message(self, op_id, claim_id, rel_type="IMPL"):
161
+ """Get cavity message (natural params), default (0,0)."""
162
+ return self.messages.get((op_id, claim_id, rel_type), (0.0, 0.0))
163
+
164
+ def _set_message(self, op_id, claim_id, msg_alpha, msg_beta, rel_type="IMPL"):
165
+ self.messages[(op_id, claim_id, rel_type)] = (msg_alpha, msg_beta)
166
+
167
+ def _get_posterior(self, claim_id):
168
+ """Get claim posterior (α, β), default Beta(1,1)."""
169
+ return self.posteriors.get(claim_id, (1.0, 1.0))
170
+
171
+ def _set_posterior(self, claim_id, alpha, beta):
172
+ self.posteriors[claim_id] = (alpha, beta)
173
+
174
+ # ── Cavity distribution ───────────────────────────────────────
175
+
176
+ def _cavity(self, claim_id, op_id, rel_type):
177
+ """Posterior minus factor message = cavity (in natural params)."""
178
+ post_alpha, post_beta = self._get_posterior(claim_id)
179
+ post_eta = self._natural_from_beta(post_alpha, post_beta)
180
+ msg_eta = self._get_message(op_id, claim_id, rel_type)
181
+ cav_eta = (post_eta[0] - msg_eta[0], post_eta[1] - msg_eta[1])
182
+ return self._beta_from_natural(*cav_eta)
183
+
184
+ # ── Gate 3: particle lifecycle ────────────────────────────────
185
+
186
+ def _init_particles(self, claim_id, alpha, beta):
187
+ """Sample n_particles from Beta(α,β), store in logit space."""
188
+ self.key, subkey = jrandom.split(self.key)
189
+ c = jrandom.beta(subkey, alpha, beta, (self.n_particles,))
190
+ y = jnp.log(c + 1e-8) - jnp.log(1 - c + 1e-8)
191
+ self._particles[claim_id] = y
192
+ self._stale[claim_id] = 0
193
+ return y
194
+
195
+ def _get_particles(self, claim_id, alpha, beta):
196
+ """Get or initialize particles. Re-expands from summary if compressed."""
197
+ if claim_id in self._particles:
198
+ self._stale[claim_id] = 0 # mark active
199
+ return self._particles[claim_id]
200
+ if claim_id in self._summaries:
201
+ # Re-expand from stored Beta summary
202
+ summ_a, summ_b = self._summaries[claim_id]
203
+ return self._init_particles(claim_id, summ_a, summ_b)
204
+ return self._init_particles(claim_id, alpha, beta)
205
+
206
+ def _maybe_compress(self, claim_id):
207
+ """Compress particles to Beta summary if stale > threshold."""
208
+ if claim_id not in self._particles:
209
+ return
210
+ self._stale[claim_id] = self._stale.get(claim_id, 0) + 1
211
+ if self._stale[claim_id] >= self.compress_after:
212
+ y = self._particles.pop(claim_id)
213
+ c = sigmoid(y)
214
+ m1 = float(jnp.mean(c))
215
+ m2 = float(jnp.mean(c ** 2))
216
+ self._summaries[claim_id] = moments_to_beta_params(m1, m2)
217
+ del self._stale[claim_id]
218
+
219
+ def _has_particles(self, claim_id):
220
+ """Check if claim has active particles (not compressed)."""
221
+ return claim_id in self._particles
222
+
223
+ def compress_all(self):
224
+ """Force-compress all active particles to Beta summaries."""
225
+ for cid in list(self._particles.keys()):
226
+ y = self._particles.pop(cid)
227
+ c = sigmoid(y)
228
+ m1 = float(jnp.mean(c))
229
+ m2 = float(jnp.mean(c ** 2))
230
+ self._summaries[cid] = moments_to_beta_params(m1, m2)
231
+ self._stale.pop(cid, None)
232
+
233
+ def expand_all(self):
234
+ """Re-expand all compressed claims from summaries."""
235
+ for cid, (a, b) in list(self._summaries.items()):
236
+ self._init_particles(cid, a, b)
237
+ del self._summaries[cid]
238
+
239
+ # ── Per-factor SVGD tilt ──────────────────────────────────────
240
+
241
+ def _tilt(self, y_a, y_b, cav_alpha_a, cav_beta_a,
242
+ cav_alpha_b, cav_beta_b, op_type, weight):
243
+ """Run SVGD on the tilted distribution for one factor."""
244
+ is_nand = 1.0 if op_type == "NAND" else 0.0
245
+ # Pass cavity params explicitly so JAX can trace once
246
+ for _ in range(self.n_svgd_steps):
247
+ y = jnp.stack([y_a, y_b], axis=-1)
248
+ grad_lp = _tilt_grad_batch(
249
+ y, cav_alpha_a, cav_beta_a, cav_alpha_b, cav_beta_b,
250
+ is_nand, weight
251
+ )
252
+ h = median_heuristic(y) + 0.1
253
+ phi = svgd_update(y, grad_lp, h)
254
+ y = y + self.svgd_lr * phi
255
+ y_a, y_b = y[:, 0], y[:, 1]
256
+ return y_a, y_b
257
+
258
+ # ── Single-factor SVBP update ─────────────────────────────────
259
+
260
+ def _update_factor(self, op_id, op_type, input_ids, weight=1.0):
261
+ """One SVBP iteration for a single factor.
262
+
263
+ Steps: cavity → tilt → project → damp → write back.
264
+ """
265
+ if len(input_ids) < 2:
266
+ return
267
+ if len(input_ids) > 2:
268
+ # ponytail: pairwise decomposition with unique sub-operator IDs
269
+ # to avoid message key collision (each pair gets its own messages).
270
+ for i in range(len(input_ids)):
271
+ for j in range(i + 1, len(input_ids)):
272
+ sub_op_id = f"{op_id}_{i}_{j}"
273
+ self._update_factor(sub_op_id, op_type,
274
+ [input_ids[i], input_ids[j]], weight)
275
+ return
276
+
277
+ id_a, id_b = input_ids
278
+
279
+ # 1. Cavity
280
+ cav_a = self._cavity(id_a, op_id, op_type)
281
+ cav_b = self._cavity(id_b, op_id, op_type)
282
+
283
+ # 2. Get/init particles from cavity
284
+ y_a = self._get_particles(id_a, *cav_a)
285
+ y_b = self._get_particles(id_b, *cav_b)
286
+
287
+ # 3. Tilt: SVGD on cavity × factor
288
+ y_a_new, y_b_new = self._tilt(
289
+ y_a, y_b, *cav_a, *cav_b, op_type, weight
290
+ )
291
+
292
+ # Store updated particles
293
+ self._particles[id_a] = y_a_new
294
+ self._particles[id_b] = y_b_new
295
+ self._stale[id_a] = 0
296
+ self._stale[id_b] = 0
297
+
298
+ # 4. Project: fit Beta to particles
299
+ c_a = sigmoid(y_a_new)
300
+ c_b = sigmoid(y_b_new)
301
+ m1_a = float(jnp.mean(c_a))
302
+ m2_a = float(jnp.mean(c_a ** 2))
303
+ m1_b = float(jnp.mean(c_b))
304
+ m2_b = float(jnp.mean(c_b ** 2))
305
+
306
+ new_post_a = moments_to_beta_params(m1_a, m2_a)
307
+ new_post_b = moments_to_beta_params(m1_b, m2_b)
308
+
309
+ # 5. New message = tilted posterior - cavity (in natural params)
310
+ new_post_eta_a = self._natural_from_beta(*new_post_a)
311
+ cav_eta_a = self._natural_from_beta(*cav_a)
312
+ raw_eta_a = (new_post_eta_a[0] - cav_eta_a[0],
313
+ new_post_eta_a[1] - cav_eta_a[1])
314
+
315
+ new_post_eta_b = self._natural_from_beta(*new_post_b)
316
+ cav_eta_b = self._natural_from_beta(*cav_b)
317
+ raw_eta_b = (new_post_eta_b[0] - cav_eta_b[0],
318
+ new_post_eta_b[1] - cav_eta_b[1])
319
+
320
+ # 6. Damp
321
+ d = self.damping
322
+ old_eta_a = self._get_message(op_id, id_a, op_type)
323
+ old_eta_b = self._get_message(op_id, id_b, op_type)
324
+
325
+ damped_a = (d * raw_eta_a[0] + (1 - d) * old_eta_a[0],
326
+ d * raw_eta_a[1] + (1 - d) * old_eta_a[1])
327
+ damped_b = (d * raw_eta_b[0] + (1 - d) * old_eta_b[0],
328
+ d * raw_eta_b[1] + (1 - d) * old_eta_b[1])
329
+
330
+ # Clamp to prevent drift
331
+ clamp = 1000
332
+ damped_a = (max(min(damped_a[0], clamp), -clamp),
333
+ max(min(damped_a[1], clamp), -clamp))
334
+ damped_b = (max(min(damped_b[0], clamp), -clamp),
335
+ max(min(damped_b[1], clamp), -clamp))
336
+
337
+ # 7. Write back
338
+ self._set_message(op_id, id_a, *damped_a, op_type)
339
+ self._set_message(op_id, id_b, *damped_b, op_type)
340
+
341
+ # 8. Update claim posteriors
342
+ self._update_claim_posterior(id_a)
343
+ self._update_claim_posterior(id_b)
344
+
345
+ def _update_claim_posterior(self, claim_id):
346
+ """Sum all incoming messages + fixed evidence prior → posterior."""
347
+ # Start from evidence prior (natural params)
348
+ ev_alpha, ev_beta = self.evidence_prior.get(claim_id, (1.0, 1.0))
349
+ total_eta1, total_eta2 = self._natural_from_beta(ev_alpha, ev_beta)
350
+ for (op_id, cid, rel_type), (ma, mb) in self.messages.items():
351
+ if cid == claim_id:
352
+ total_eta1 += ma
353
+ total_eta2 += mb
354
+ alpha, beta = self._beta_from_natural(total_eta1, total_eta2)
355
+ self._set_posterior(claim_id, alpha, beta)
356
+
357
+ # ── Public API ────────────────────────────────────────────────
358
+
359
+ def compute_confidence(self, claim_id):
360
+ """Return {mean, variance, alpha, beta} for a claim."""
361
+ a, b = self._get_posterior(claim_id)
362
+ total = a + b
363
+ if total <= 0:
364
+ # #330: degenerate posterior (0,0) — uniform Beta(1,1) fallback
365
+ # instead of ZeroDivisionError.
366
+ return {"mean": 0.5, "variance": 1/12, "alpha": a, "beta": b}
367
+ return {
368
+ "mean": a / total,
369
+ "variance": (a * b) / (total * total * (total + 1)),
370
+ "alpha": a,
371
+ "beta": b,
372
+ }
373
+
374
+ @property
375
+ def stats(self):
376
+ """Return compression/memory stats for Gate 3 monitoring."""
377
+ return {
378
+ "active_particles": len(self._particles),
379
+ "compressed": len(self._summaries),
380
+ "total_claims": len(self.posteriors),
381
+ "particle_bytes": sum(y.nbytes for y in self._particles.values()),
382
+ "summary_bytes": len(self._summaries) * 16, # 2 floats × 8 bytes
383
+ }
384
+
385
+ def run(self, factors, evidence=None, warm_start=False):
386
+ """Run SVBP on a list of factors.
387
+
388
+ Args:
389
+ factors: list of (op_id, op_type, [input_ids], weight).
390
+ evidence: dict of {claim_id: (alpha, beta)} for evidence priors.
391
+ warm_start: if True, reuse existing particles/summaries.
392
+ if False (cold start), clear all state first.
393
+ Returns:
394
+ (iterations, converged).
395
+ """
396
+ if not warm_start:
397
+ self.messages.clear()
398
+ self.posteriors.clear()
399
+ self._particles.clear()
400
+ self._summaries.clear()
401
+ self._stale.clear()
402
+
403
+ # Set fixed evidence priors (never overwritten)
404
+ if evidence:
405
+ self.evidence_prior = dict(evidence)
406
+
407
+ if warm_start:
408
+ # Recompute posteriors from evidence + existing messages
409
+ # (don't reset to evidence-only — that would discard message-passing work)
410
+ all_cids = set(self.evidence_prior.keys()) | {cid for (_, cid, _) in self.messages}
411
+ for cid in all_cids:
412
+ self._update_claim_posterior(cid)
413
+ else:
414
+ # Cold start: posteriors = evidence priors only
415
+ for cid, (alpha, beta) in self.evidence_prior.items():
416
+ self._set_posterior(cid, alpha, beta)
417
+
418
+ prev = {cid: self._get_posterior(cid) for cid in self.posteriors}
419
+
420
+ import random
421
+ for iteration in range(self.max_iter):
422
+ random.shuffle(factors)
423
+ for op_id, op_type, input_ids, weight in factors:
424
+ self._update_factor(op_id, op_type, input_ids, weight)
425
+
426
+ # Gate 3: compress stale claims
427
+ for op_id, op_type, input_ids, weight in factors:
428
+ for cid in input_ids:
429
+ self._maybe_compress(cid)
430
+
431
+ # Convergence check (only active posteriors)
432
+ max_change = 0.0
433
+ for cid in self.posteriors:
434
+ new_a, new_b = self._get_posterior(cid)
435
+ old_a, old_b = prev.get(cid, (1.0, 1.0))
436
+ change = max(
437
+ abs(new_a - old_a) / max(old_a, 1e-6),
438
+ abs(new_b - old_b) / max(old_b, 1e-6),
439
+ )
440
+ max_change = max(max_change, change)
441
+ prev[cid] = (new_a, new_b)
442
+
443
+ if max_change < self.tol:
444
+ return iteration + 1, True
445
+
446
+ return self.max_iter, False
tortoise/taxonomy.py ADDED
@@ -0,0 +1,71 @@
1
+ """Taxonomy tools — read-only entity counting and domain enumeration.
2
+
3
+ P0-5 tortoise_taxonomy, P0-6 tortoise_list_domains, P0-7 tortoise_list_topics.
4
+ One Cypher query per tool. No mutations.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+
11
+ def taxonomy(proj) -> dict[str, int]:
12
+ """Count entities by node label. Returns {Point: N, Event: N, ...}."""
13
+ labels = ("Point", "Event", "Subject", "Object", "Document")
14
+ result: dict[str, int] = {}
15
+ for label in labels:
16
+ n = proj.g.query(f"MATCH (n:{label}) RETURN count(n)").result_set[0][0]
17
+ result[label] = n
18
+ return result
19
+
20
+
21
+ def list_topics(proj, entity_id: str) -> dict:
22
+ """entityProfile lite: connected topics grouped by kind.
23
+
24
+ Returns {entity, pointKind, neighbors: [{pointKind}], neighborCounts: {kind: N}}.
25
+ """
26
+ entity = proj.g.query(
27
+ "MATCH (n:Point {id:$id}) RETURN properties(n)",
28
+ params={"id": entity_id},
29
+ ).result_set
30
+ if not entity:
31
+ return {"error": f"Entity {entity_id} not found"}
32
+
33
+ props = entity[0][0]
34
+
35
+ # Connected neighbors via operators (2-hop: n ← operator → m)
36
+ # ponytail: split into two directed queries — FalkorDB undirected
37
+ # multi-rel-type patterns are unreliable across versions.
38
+ neighbors_impl = proj.g.query(
39
+ "MATCH (n:Point {id:$id})<-[r1:IMPL]-(op:Point {is_operator:true})"
40
+ "-[r2:IMPL]->(m:Point) "
41
+ "WHERE m.id <> n.id AND (m.is_operator IS NULL OR m.is_operator = false) "
42
+ "RETURN m.pointKind",
43
+ params={"id": entity_id},
44
+ ).result_set
45
+ neighbors_nand = proj.g.query(
46
+ "MATCH (n:Point {id:$id})<-[r1:NAND]-(op:Point {is_operator:true})"
47
+ "-[r2:NAND]->(m:Point) "
48
+ "WHERE m.id <> n.id AND (m.is_operator IS NULL OR m.is_operator = false) "
49
+ "RETURN m.pointKind",
50
+ params={"id": entity_id},
51
+ ).result_set
52
+ neighbors = neighbors_impl + neighbors_nand
53
+
54
+ neighbor_list = [
55
+ {"pointKind": r[0]}
56
+ for r in neighbors if r[0] is not None
57
+ ]
58
+
59
+ # Count by kind
60
+ kind_counts: dict[str, int] = {}
61
+ for n in neighbor_list:
62
+ k = n["pointKind"] or "unknown"
63
+ kind_counts[k] = kind_counts.get(k, 0) + 1
64
+
65
+ return {
66
+ "id": props.get("id"),
67
+ "pointKind": props.get("pointKind"),
68
+ "content": props.get("content", "")[:200], # ponytail: preview, not full
69
+ "neighbors": neighbor_list,
70
+ "neighborCounts": kind_counts,
71
+ }