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/sdk.py ADDED
@@ -0,0 +1,4713 @@
1
+ """Tortoise SDK — Layer 1 facade for Tortoise epistemic graph interaction.
2
+
3
+ Wraps FalkorProjection (Docker/server FalkorDB by default, embedded via path argument).
4
+ Lazy-opens on first call. Returns structured dicts, never raw FalkorDB result sets.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json as _json
10
+ import logging
11
+ import re
12
+ from typing import Any
13
+
14
+ from .domain_loader import known_kinds, register_kind
15
+ from .ids import ulid
16
+ from . import monitoring
17
+ from .projection import FalkorProjection
18
+ import threading
19
+
20
+ # P0 Group 3: register custom kinds for diary + checkpoint
21
+ register_kind("diary")
22
+ register_kind("checkpoint-item")
23
+ register_kind("option") # used by file_decision (#133)
24
+ register_kind("evidence") # used by file_decision (#133)
25
+
26
+ # Valid status values for Point nodes (used by update_point status validation)
27
+ POINT_STATUS_VALUES = frozenset({'live', 'draft', 'outdated', 'archived'})
28
+
29
+ _logger = logging.getLogger(__name__)
30
+
31
+
32
+ def _sanitize_props(props: dict, *, reject_id: bool = False) -> dict:
33
+ """#329: reject server-managed fields on tenant write surfaces.
34
+
35
+ ``sourcePath``/``source_path`` are server-filesystem fields consumed by the
36
+ operator ``--upgrade-all`` path (projection maps ``source_path`` →
37
+ ``d.sourcePath`` via ``_DOCUMENT_HANDLED``); a tenant setting them turns the
38
+ graph into a file-read oracle. ``id`` overrides on entity surfaces mutate
39
+ node identity / mint tenant-chosen Document ids. Both are rejected with a
40
+ clear ValueError (fail-closed). ``api.add_document``'s explicit
41
+ ``source_path`` parameter is UNTOUCHED — this only guards props passthrough.
42
+ """
43
+ props = dict(props)
44
+ for key in ("sourcePath", "source_path"):
45
+ if key in props:
46
+ raise ValueError(
47
+ f"{key!r} is a server-managed field and cannot be set via props."
48
+ )
49
+ if reject_id and "id" in props:
50
+ raise ValueError("'id' is server-managed and cannot be set via props.")
51
+ return props
52
+
53
+
54
+ def _coerce_props(props: dict) -> dict:
55
+ """Flatten a nested 'props' dict into top-level keyword props, in place.
56
+
57
+ The MCP server passes props= through as-is (shallow copy, no flatten), so
58
+ this helper is the single place that handles both conventions. Direct SDK
59
+ callers naturally mirror the MCP tool signature and pass props={"k": v}.
60
+ FalkorDB rejects non-primitive property values, so a dict-valued 'props'
61
+ keyword would otherwise fail with
62
+ "Property values can only be of primitive types". Accept both conventions:
63
+
64
+ - props={"k": v} -> k, v merged into top-level props
65
+ - props=None -> no-op (MCP convention for absent props)
66
+ - flattened kwargs -> unchanged
67
+
68
+ A non-dict, non-None 'props' value (e.g. a string) is preserved as a literal
69
+ property named 'props' — scalars are legal FalkorDB property values.
70
+ """
71
+ nested = props.pop("props", None)
72
+ if isinstance(nested, dict):
73
+ # Explicit top-level kwargs are the caller's more specific intent —
74
+ # they win over nested props on collision (mirrors the MCP server,
75
+ # where explicit tool args override user-supplied props).
76
+ props.update({k: v for k, v in nested.items() if k not in props})
77
+ elif nested is not None:
78
+ # Scalar 'props' value — restore as a literal property.
79
+ props["props"] = nested
80
+ return props
81
+
82
+
83
+ # ── ULID validation (Issue #52) ──
84
+ # Canonical format (from tortoise/ids.py): <timestamp-hex>-<uuid12>
85
+ _ULID_RE = re.compile(r"^[0-9a-f]+-[0-9a-f]{12}$")
86
+ # Standard Crockford base32 ULID (26 chars) — recognized as valid
87
+ _CROCKFORD_ULID_RE = re.compile(r"^[0-7][0-9A-HJKMNP-TV-Z]{25}$", re.IGNORECASE)
88
+
89
+
90
+ def _is_ulid(s: str) -> bool:
91
+ """Return True if *s* matches a valid ULID format (canonical or Crockford)."""
92
+ return bool(_ULID_RE.match(s) or _CROCKFORD_ULID_RE.match(s))
93
+
94
+
95
+ def _content_hash(text: str) -> str:
96
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
97
+
98
+
99
+ def _to_iso_utc(value) -> str:
100
+ """Normalize a datetime or ISO-8601 string to UTC ISO-8601 (with +00:00).
101
+
102
+ AgentSession startedAt values are stored via
103
+ ``datetime.now(timezone.utc).isoformat()`` (e.g.
104
+ ``2026-08-07T01:20:50.123456+00:00``), so a canonical, timezone-stripped-
105
+ to-UTC string keeps ``>=`` / ``<=`` lexicographic comparisons valid regardless
106
+ of the caller's local timezone or whether they passed ``Z`` or an offset.
107
+ """
108
+ from datetime import datetime, timezone
109
+ if isinstance(value, datetime):
110
+ dt = value
111
+ if dt.tzinfo is None:
112
+ dt = dt.replace(tzinfo=timezone.utc)
113
+ else:
114
+ dt = dt.astimezone(timezone.utc)
115
+ return dt.isoformat()
116
+ # ISO-8601 string — normalize any timezone/offset to UTC. A naive string
117
+ # (no offset suffix) is treated as UTC, mirroring the naive-datetime
118
+ # branch — NOT as local time (which would shift the filter window by the
119
+ # caller's offset; #243/#244 review).
120
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
121
+ if dt.tzinfo is None:
122
+ dt = dt.replace(tzinfo=timezone.utc)
123
+ return dt.astimezone(timezone.utc).isoformat()
124
+
125
+
126
+ def _save_progress(progress_file: str, directory: str, total: int, processed: int,
127
+ ingested: int, updated: int, skipped: int, failed: int,
128
+ errors: list[dict],
129
+ completed_files: list[str] | None = None) -> None:
130
+ """Save batch indexing progress for resumability."""
131
+ from datetime import datetime, timezone
132
+ try:
133
+ with open(progress_file, 'w') as f:
134
+ _json.dump({
135
+ "started": datetime.now(timezone.utc).isoformat(),
136
+ "directory": directory,
137
+ "total_files": total,
138
+ "processed": processed,
139
+ "ingested": ingested,
140
+ "updated": updated,
141
+ "skipped": skipped,
142
+ "failed": failed,
143
+ "completed_files": completed_files or [],
144
+ "errors": errors[-20:], # keep last 20 errors
145
+ }, f, indent=2)
146
+ except Exception:
147
+ pass # progress file is best-effort
148
+
149
+
150
+ # Module-level cached registry for kind expansion
151
+ _registry_cache: "PackRegistry | None" = None
152
+ _registry_lock = threading.Lock()
153
+
154
+
155
+ def _get_kind_expander():
156
+ """Return cached PackRegistry with pre-computed expansion table."""
157
+ global _registry_cache
158
+ if _registry_cache is None:
159
+ with _registry_lock:
160
+ if _registry_cache is None:
161
+ from .pack_registry import PackRegistry
162
+ from pathlib import Path as _Path
163
+ packs_dir = _Path(__file__).resolve().parent.parent / "packs"
164
+ _registry_cache = PackRegistry(packs_dir)
165
+ _registry_cache.load_all()
166
+ return _registry_cache
167
+
168
+
169
+ class TortoiseSDK:
170
+ """Layer 1 facade for Tortoise epistemic graph interaction.
171
+
172
+ Args:
173
+ db_path: Optional path to FalkorDBLite database file (None = use TORTOISE_DB_URI env var).
174
+ namespace: Optional namespace for graph-name isolation.
175
+
176
+ Precedence: an explicitly-provided db_path wins over the TORTOISE_DB_URI
177
+ env var. This lets tests/fixtures force a temp embedded DB even when a
178
+ shared test URI is set in the environment (#139).
179
+ """
180
+
181
+ def __init__(self, db_path: str | None = None, *, namespace: str | None = None):
182
+ import os, re
183
+ db_uri = os.environ.get("TORTOISE_DB_URI")
184
+ if db_uri and db_path is None:
185
+ self._db_path = None
186
+ self._db_uri = db_uri
187
+ else:
188
+ # P0: Crash early if running in production with no database configured.
189
+ # Embedded redislite has no persistent volume → all data lost on deploy.
190
+ # Must evaluate BEFORE resolve_db_path() fills in the default.
191
+ if not db_uri and not db_path:
192
+ if os.environ.get("FLY_APP_NAME"):
193
+ raise RuntimeError(
194
+ "TORTOISE_DB_URI is empty in production. "
195
+ "Set FALKORDB_PASSWORD (recommended: entrypoint.sh auto-constructs the URI) "
196
+ "or set TORTOISE_DB_URI directly. "
197
+ "See docs/infra-runbook.md §1."
198
+ )
199
+ # Dev/CI: proceed, will use embedded redislite (tests set their own URI)
200
+ # Task 6 wiring (issue #176): when neither a path nor a URI is
201
+ # given, default to the canonical embedded path via resolve_db_path()
202
+ # so the SDK is not blind to TORTOISE_DB_PATH.
203
+ if db_path is None and not db_uri:
204
+ from tortoise.config import resolve_db_path
205
+ db_path = resolve_db_path()
206
+ self._db_path = db_path
207
+ self._db_uri = None
208
+ # Namespace isolation: prefix graph name to segregate data
209
+ if namespace is not None:
210
+ if not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$', namespace):
211
+ raise ValueError(
212
+ f"Invalid namespace {namespace!r}. "
213
+ "Use alphanumeric, hyphens, underscores; max 64 chars."
214
+ )
215
+ self._namespace = namespace
216
+ self._proj: FalkorProjection | None = None
217
+ self._ep = None # lazy-init TortoiseEP
218
+ self._evidence: dict[str, tuple[float, float]] = {}
219
+ self._registry_g = None
220
+ self._audit_logger = None
221
+ # Dreaming (#85): dirty claim roots awaiting EP stabilization. Write
222
+ # paths mark affected claims dirty; dream()/lazy-read consume them.
223
+ self._dirty_roots: set[str] = set()
224
+ self._dreamer = None # lazy-init Dreamer
225
+
226
+ def _get_proj(self) -> FalkorProjection:
227
+ if self._proj is None:
228
+ # Resolve the URI's own graph name first (used as the fallback
229
+ # when no namespace is set — preserves the conftest per-session
230
+ # test graph, #221).
231
+ uri_graph: str | None = None
232
+ if self._db_uri is not None:
233
+ from urllib.parse import urlparse
234
+ uri_graph = urlparse(self._db_uri).path.lstrip('/') or "tortoise"
235
+
236
+ if self._namespace == "registry":
237
+ # Control-plane SDK: shared registry main graph.
238
+ graph_name = "registry_tortoise"
239
+ elif self._namespace:
240
+ if self._namespace.startswith(("test_", "tortoise_test")):
241
+ # Test namespace: isolate on a test-prefixed graph so the
242
+ # _assert_test_graph guard still passes (#221). Matches the
243
+ # historical {ns}_tortoise naming.
244
+ graph_name = f"{self._namespace}_tortoise"
245
+ else:
246
+ # Team SDK: isolated team graph (matches provision's
247
+ # team_{team_id} namespace creation, #7886).
248
+ graph_name = f"team_{self._namespace}"
249
+ else:
250
+ # No namespace: honor the URI's own graph (the conftest
251
+ # session graph for tests). Fixes #7886 regression that
252
+ # hardcoded 'tortoise' and clobbered the test graph.
253
+ graph_name = uri_graph or "tortoise"
254
+ if self._db_uri is not None:
255
+ # Multi-tenant isolation (#7886): pass the namespaced graph
256
+ # name so tenants never share the URI's default graph.
257
+ self._proj = FalkorProjection.from_uri(self._db_uri, graph_name=graph_name)
258
+ else:
259
+ self._proj = FalkorProjection(self._db_path, graph_name=graph_name)
260
+ return self._proj
261
+
262
+ def test_guard(self) -> None:
263
+ """Assert the connected graph is safe for destructive test teardowns.
264
+
265
+ Raises RuntimeError if the graph appears to be a production graph
266
+ (named ``tortoise`` or ``tortoise_restored_*``). Test fixtures
267
+ should call this before any ``MATCH (n) DETACH DELETE n``.
268
+
269
+ Override with ``TORTOISE_ALLOW_PRODUCTION=1``.
270
+ """
271
+ import os
272
+ if os.environ.get("TORTOISE_ALLOW_PRODUCTION") == "1":
273
+ return
274
+
275
+ proj = self._get_proj()
276
+ graph_name = getattr(proj, "graph_name", None)
277
+ if graph_name is None:
278
+ graph_name = getattr(proj.g, "name", "unknown")
279
+
280
+ # Block destructive ops on production graphs:
281
+ # tortoise — the real graph
282
+ # tortoise_restored_* — restored snapshots (precious)
283
+ blocked = (
284
+ graph_name == "tortoise"
285
+ or graph_name.startswith("tortoise_restored")
286
+ )
287
+ if blocked:
288
+ raise RuntimeError(
289
+ f"SAFETY GUARD: Destructive operation blocked on graph "
290
+ f"'{graph_name}'. This appears to be a production graph. "
291
+ f"Use an isolated test graph (e.g. "
292
+ f"'tortoise_test_calibration') instead. "
293
+ f"Override with TORTOISE_ALLOW_PRODUCTION=1."
294
+ )
295
+
296
+ def _get_registry(self):
297
+ """Return the control_plane registry graph handle (cached).
298
+
299
+ Uses the existing db connection — no second FalkorDB connection.
300
+ Registry graph name is namespace-scoped (``{ns}_control_plane``) so
301
+ different namespaces never share registry state, and test graphs get
302
+ an isolated name (``{ns}_{test_graph}_control_plane``) so parallel
303
+ test runs stay independent (#135, #139).
304
+ """
305
+ if self._registry_g is None:
306
+ proj = self._get_proj()
307
+ graph_name = getattr(proj, "graph_name", None)
308
+ ns = self._namespace or ""
309
+ if graph_name and graph_name.startswith(("tortoise_test_", "test_")):
310
+ # Keep the test prefix so test-graph guards still apply.
311
+ registry_name = f"{ns}_{graph_name}_control_plane" if ns else f"{graph_name}_control_plane"
312
+ elif ns:
313
+ registry_name = f"{ns}_control_plane"
314
+ else:
315
+ registry_name = "control_plane"
316
+ self._registry_g = proj.db.select_graph(registry_name)
317
+ self._ensure_registry_indexes()
318
+ return self._registry_g
319
+
320
+ def _ensure_registry_indexes(self) -> None:
321
+ """Create indexes on registry graph labels (idempotent)."""
322
+ g = self._registry_g
323
+ if g is None:
324
+ return
325
+ indexes = [
326
+ ("Team", "name"),
327
+ ("Membership", "team_id"),
328
+ ("Membership", "user_id"),
329
+ ("APIKey", "team_id"),
330
+ ("APIKey", "key_hash"),
331
+ ("Invitation", "team_id"),
332
+ ("Invitation", "token_hash"),
333
+ ]
334
+ for label, prop in indexes:
335
+ try:
336
+ g.query(f"CREATE INDEX FOR (n:{label}) ON (n.{prop})")
337
+ except Exception:
338
+ _logger.debug("Index may already exist: %s.%s", label, prop)
339
+
340
+ # ── Core CRUD ─────────────────────────────────────────────────
341
+
342
+ def _sync_tags(self, proj: FalkorProjection, pid: str, tags) -> None:
343
+ """Reconcile TAGGED edges for a point against a tags value (#485).
344
+
345
+ Idempotent: MERGE creates any missing :Tag nodes + TAGGED edges, and
346
+ edges to tags no longer in the list are deleted. Only list values are
347
+ synced — matching create_point's behavior, a non-list tag value is
348
+ stored as a plain property but gets no edges (and leaves existing
349
+ edges untouched).
350
+ """
351
+ if not isinstance(tags, list):
352
+ return
353
+ for tag in tags:
354
+ proj.g.query(
355
+ "MATCH (p:Point {id:$pid}) "
356
+ "MERGE (t:Tag {name:$tag}) "
357
+ "MERGE (p)-[:TAGGED]->(t)",
358
+ params={"pid": pid, "tag": tag},
359
+ )
360
+ # Delete edges to tags no longer in the list (diff via graph read to
361
+ # avoid list-parameter IN-clause portability concerns on FalkorDB).
362
+ stale = proj.g.query(
363
+ "MATCH (p:Point {id:$pid})-[:TAGGED]->(t:Tag) RETURN t.name",
364
+ params={"pid": pid},
365
+ ).result_set
366
+ removed = 0
367
+ for row in stale:
368
+ if row[0] not in tags:
369
+ proj.g.query(
370
+ "MATCH (p:Point {id:$pid})-[r:TAGGED]->(t:Tag {name:$tag}) "
371
+ "DELETE r",
372
+ params={"pid": pid, "tag": row[0]},
373
+ )
374
+ removed += 1
375
+ # GC orphaned :Tag nodes when the sync actually removed edges — tag
376
+ # removal can leave a Tag with no TAGGED referrers (#485). Skipped on
377
+ # create_point (no stale edges there), so new-point creation never pays
378
+ # the scan.
379
+ if removed:
380
+ proj.g.query("MATCH (t:Tag) WHERE NOT (t)<-[:TAGGED]-() DELETE t")
381
+
382
+ def create_point(self, kind: str, content: str, **props) -> dict:
383
+ """Create a new Point node. Raises ValueError if kind is invalid.
384
+
385
+ Set dedup=True for idempotent creation (matches by content hash).
386
+ """
387
+ self._validate_kind(kind)
388
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
389
+ # #329: server-managed fields rejected on the props passthrough
390
+ # (the explicit-id path via props.pop("id") below is preserved for operators)
391
+ props = _sanitize_props(props)
392
+ from datetime import datetime, timezone
393
+ now = datetime.now(timezone.utc).isoformat()
394
+ proj = self._get_proj()
395
+
396
+ # #49 Phase 2: context is REMOVED — raise TypeError if passed
397
+ if "context" in props:
398
+ raise TypeError(
399
+ "create_point() got unexpected keyword argument 'context'. "
400
+ "Context has been removed. Use pointKind for filtering, "
401
+ "anchors for EP scoping, extractedFrom for provenance. See #49."
402
+ )
403
+
404
+ # Calibration: pop credibility before storing as node property
405
+ credibility = props.pop("credibility", None)
406
+ # Always compute and store content hash — dedup flag only gates the
407
+ # existing-point lookup, not hash persistence (fix #80).
408
+ ch = _content_hash(content)
409
+ props["content_hash"] = ch
410
+ # Idempotency guard: dedup by content hash when requested
411
+ dedup = props.pop("dedup", False)
412
+ if dedup:
413
+ ch = _content_hash(content)
414
+ # P1 #49: dedup by content_hash + pointKind (NOT context, which is no longer written)
415
+ existing = proj.g.query(
416
+ "MATCH (n:Point {content_hash:$ch}) "
417
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
418
+ "AND n.pointKind = $kind "
419
+ "RETURN n.id",
420
+ params={"ch": ch, "kind": kind},
421
+ ).result_set
422
+ if existing:
423
+ pid = existing[0][0]
424
+ # Existing point already stores content_hash — don't re-write it
425
+ # (would make the `if props:` guard always truthy and bump
426
+ # updatedAt on every dedup hit, #80 review).
427
+ props.pop("content_hash", None)
428
+ if credibility is not None:
429
+ _logger.warning(
430
+ "credibility=%r ignored — point %s already exists and dedup=True",
431
+ credibility, pid)
432
+ if props:
433
+ # Only touch the existing point when the caller passed
434
+ # other props — a pure dedup hit (no props) must not bump
435
+ # updatedAt or re-trigger EP dirty-marking (#490 review
436
+ # P2-1: re-capture would churn confidence for every point).
437
+ props["updatedAt"] = now
438
+ self.update_point(pid, **props)
439
+ return self.get_point(pid)
440
+
441
+ # Issue #52 — warn when caller passes an explicit non-ULID id
442
+ explicit_id = props.pop("id", None)
443
+ if explicit_id is not None:
444
+ if not _is_ulid(explicit_id):
445
+ _logger.warning(
446
+ "create_point received non-ULID id=%r — canonical format is "
447
+ "<timestamp-hex>-<uuid12>. This will override the auto-generated ULID. "
448
+ "Prefer omitting 'id' to use auto-generated ULID.",
449
+ explicit_id,
450
+ )
451
+ pid = explicit_id
452
+ else:
453
+ pid = ulid()
454
+ # Points enter as draft, go live when first edge is created (#131)
455
+ status = props.pop("status", "draft")
456
+
457
+ # Compute embedding (Phase 1A, #7698) — stored as Point property
458
+ embedding = None
459
+ try:
460
+ from .embeddings import compute_embedding
461
+ embedding = compute_embedding(content)
462
+ except Exception:
463
+ pass # Graceful — embedding is optional
464
+
465
+ proj.g.query(
466
+ "CREATE (n:Point {id:$id, content:$c, pointKind:$k, "
467
+ "is_operator:false, status:$st, createdAt:$now, updatedAt:$now}) "
468
+ "SET n.embedding = vecf32($embedding)",
469
+ params={"id": pid, "c": content, "k": kind, "st": status, "now": now,
470
+ "embedding": embedding},
471
+ )
472
+ # Tag handling: create :Tag nodes + TAGGED edges (#215, #485)
473
+ tags = props.get("tags") or []
474
+ if isinstance(tags, list):
475
+ self._sync_tags(proj, pid, tags)
476
+ for key, val in props.items():
477
+ proj.g.query(
478
+ "MATCH (n:Point {id:$id}) SET n += $props",
479
+ params={"id": pid, "props": {key: val}},
480
+ )
481
+ # P1-1: Ontology v2.1 — link Point → Source via extractedFrom
482
+ if props.get("extractedFrom"):
483
+ proj._link_source(pid, props["extractedFrom"])
484
+ # Inheritance gate dirty-mark: a freshly-sourced point is always
485
+ # inherit-eligible on the next EP run (no interval wait, #398).
486
+ self._invalidate_inheritance_gate([pid])
487
+
488
+ # Apply credibility baseline (only on new creation, not dedup)
489
+ if credibility is not None:
490
+ tier_map = {
491
+ "gold": (10, 1), "T0": (10, 1), 0: (10, 1),
492
+ "high": (5, 1), "T1": (5, 1), 1: (5, 1),
493
+ "medium": (3, 1), "T2": (3, 1), 2: (3, 1),
494
+ "low": (2, 1), "T3": (2, 1), 3: (2, 1),
495
+ "unverified": (1.1, 1), "T4": (1.1, 1), 4: (1.1, 1),
496
+ }
497
+ alpha, beta = tier_map.get(credibility, (1, 1))
498
+ self.set_point_baseline(pid, alpha, beta)
499
+ # Dreaming (#85): a new point can carry confidence-affecting props;
500
+ # mark it dirty so the next dream/lazy-read stabilizes it.
501
+ self._mark_dirty([pid])
502
+ return self.get_point(pid)
503
+
504
+ def create_or_update_point(self, kind: str, content: str, **props) -> dict:
505
+ """Idempotent create/update — matches by content hash."""
506
+ return self.create_point(kind, content, dedup=True, **props)
507
+
508
+ # ── Resolution helper (Issue #52) ──
509
+
510
+ def resolve_id(self, id_str: str) -> dict | None:
511
+ """Resolve any Point ID (legacy / numeric / ULID) to the canonical point.
512
+
513
+ Returns the Point dict if found, None otherwise.
514
+
515
+ Strategy:
516
+ 1. Exact match on Point.id
517
+ 2. If the id looks like a numeric reference, search by content/properties
518
+ (best-effort — legacy numeric IDs may not have explicit mappings yet)
519
+
520
+ Non-destructive — read-only operation.
521
+
522
+ Limitations:
523
+ - For legacy prefix IDs (letta-*, op-*, etc.) with no exact match,
524
+ there is currently no migration mapping to a canonical ULID.
525
+ This is a known gap covered by docs/migrations/id-normalization-plan.md.
526
+ - The resolution is exact-id-first; fuzzy matching is future work.
527
+ """
528
+ proj = self._get_proj()
529
+
530
+ # 1. Exact match
531
+ rows = proj.g.query(
532
+ "MATCH (n:Point {id: $id}) RETURN n.id, n.content, n.pointKind, n.status",
533
+ params={"id": id_str},
534
+ ).result_set
535
+ if rows:
536
+ return self.get_point(rows[0][0])
537
+
538
+ # 2. If numeric, try finding a point whose properties reference it
539
+ # (best-effort — many numeric IDs are native node IDs and would have
540
+ # matched in step 1; this handles edge cases like internal refs)
541
+ if id_str.isdigit():
542
+ # Search for points whose content or any property contains the numeric ID
543
+ rows = proj.g.query(
544
+ "MATCH (n:Point) WHERE n.content CONTAINS $id_str "
545
+ "RETURN n.id, n.content LIMIT 5",
546
+ params={"id_str": id_str},
547
+ ).result_set
548
+ if rows:
549
+ _logger.info(
550
+ "resolve_id: numeric %r not found as direct id; "
551
+ "returning best-match point %r", id_str, rows[0][0]
552
+ )
553
+ return self.get_point(rows[0][0])
554
+
555
+ return None
556
+
557
+ def update_point(self, id: str, **props) -> dict:
558
+ """Update properties on an existing Point. Returns updated point dict.
559
+
560
+ For :Object-labeled nodes, version is auto-incremented on every update.
561
+ Status changes are validated against POINT_STATUS_VALUES.
562
+ """
563
+ proj = self._get_proj()
564
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
565
+ # #329: id mutation + server-managed fields rejected
566
+ props = _sanitize_props(props, reject_id=True)
567
+
568
+ # #49 Phase 2: context is REMOVED — raise TypeError if passed
569
+ if "context" in props:
570
+ raise TypeError(
571
+ "update_point() got unexpected keyword argument 'context'. "
572
+ "Context has been removed. See #49."
573
+ )
574
+
575
+ # Validate status if present
576
+ if 'status' in props and props['status'] not in POINT_STATUS_VALUES:
577
+ raise ValueError(
578
+ f"Invalid status {props['status']!r}. "
579
+ f"Must be one of: {', '.join(sorted(POINT_STATUS_VALUES))}"
580
+ )
581
+
582
+ # Check if node carries :Object label (entity node with version tracking)
583
+ has_object = proj.g.query(
584
+ "MATCH (n:Point:Object {id:$id}) RETURN count(n) > 0",
585
+ params={"id": id},
586
+ ).result_set[0][0]
587
+
588
+ if has_object:
589
+ from datetime import datetime, timezone
590
+ now = datetime.now(timezone.utc).isoformat()
591
+ proj.g.query(
592
+ "MATCH (n:Point:Object {id:$id}) "
593
+ "SET n += $props, n.version = coalesce(n.version, 0) + 1, n.updatedAt = $now",
594
+ params={"id": id, "props": props, "now": now},
595
+ )
596
+ else:
597
+ for key, val in props.items():
598
+ proj.g.query(
599
+ "MATCH (n:Point {id:$id}) SET n += $props",
600
+ params={"id": id, "props": {key: val}},
601
+ )
602
+ # Tag sync (#485): keep TAGGED edges consistent with the n.tags
603
+ # property — update_point previously set the property but left edges
604
+ # stale, so query_points_by_tag missed updated points. Falsy tag
605
+ # values (None, "") normalize to [] like create_point, so the
606
+ # "clear tags" idiom removes edges instead of leaving them stale.
607
+ if "tags" in props:
608
+ self._sync_tags(proj, id, props["tags"] or [])
609
+ # Dreaming (#85): property mutations can affect confidence.
610
+ self._mark_dirty([id])
611
+ return self.get_point(id)
612
+
613
+ def delete_point(self, id: str) -> bool:
614
+ """Delete a Point and its relationships. Returns True if found."""
615
+ proj = self._get_proj()
616
+ exists = proj.g.query(
617
+ "MATCH (n:Point {id:$id}) RETURN count(n) > 0",
618
+ params={"id": id},
619
+ ).result_set[0][0]
620
+ if not exists:
621
+ return False
622
+ # A tag's edge count can only change for this point's own TAGGED
623
+ # edges — scope the orphan scan to that case (skips the global tag
624
+ # scan on every untagged delete; #485).
625
+ has_tag_edges = proj.g.query(
626
+ "MATCH (n:Point {id:$id})-[:TAGGED]->() RETURN count(*) > 0",
627
+ params={"id": id},
628
+ ).result_set[0][0]
629
+ proj.g.query("MATCH (n:Point {id:$id}) DETACH DELETE n", params={"id": id})
630
+ # Tag GC (#485): delete orphaned :Tag nodes (no incoming TAGGED edges).
631
+ # Idempotent — DETACH DELETE leaves count-0 tags behind that would
632
+ # otherwise accumulate in list_tags.
633
+ if has_tag_edges:
634
+ proj.g.query("MATCH (t:Tag) WHERE NOT (t)<-[:TAGGED]-() DELETE t")
635
+ # Dreaming (#85): deletion changes the graph structure around neighbors.
636
+ self._mark_dirty([id])
637
+ return True
638
+
639
+ def delete_point_wrapped(self, id: str) -> dict:
640
+ """Delete a Point. Returns dict for MCP tool consumption."""
641
+ found = self.delete_point(id)
642
+ return {"deleted": found, "id": id}
643
+
644
+ # ── Invalidate / Supersede (#6999 GAP-12) ────────────────────
645
+
646
+ def invalidate_point(self, id: str, corrected_by_id: str) -> dict:
647
+ """Mark a Point outdated, linked to its replacement via CORRECTS edge.
648
+
649
+ Validation contract (#330) — all checks run BEFORE any write so a
650
+ failure can never leave a partial graph state:
651
+ - id == corrected_by_id → ValueError (a self-CORRECTS edge poisons
652
+ traversal/credibility chains).
653
+ - old point missing (never existed or already deleted) →
654
+ {"invalidated": False} with no writes (retry-friendly).
655
+ - corrected_by point missing → ValueError (structural failure: would
656
+ orphan an outdated point with no replacement).
657
+ Re-invalidating a point that still EXISTS re-asserts (returns True,
658
+ MERGE keeps a single CORRECTS edge).
659
+ """
660
+ from datetime import datetime, timezone
661
+ proj = self._get_proj()
662
+ if id == corrected_by_id:
663
+ raise ValueError(
664
+ f"invalidate_point: corrected_by cannot be the point itself ({id!r})"
665
+ )
666
+ old_exists = proj.g.query(
667
+ "MATCH (n:Point {id:$id}) RETURN count(n) > 0", params={"id": id},
668
+ ).result_set[0][0]
669
+ if not old_exists:
670
+ return {"invalidated": False, "id": id, "corrected_by": corrected_by_id}
671
+ new_exists = proj.g.query(
672
+ "MATCH (n:Point {id:$id}) RETURN count(n) > 0",
673
+ params={"id": corrected_by_id},
674
+ ).result_set[0][0]
675
+ if not new_exists:
676
+ raise ValueError(
677
+ f"invalidate_point: corrected_by point {corrected_by_id!r} does not "
678
+ f"exist — refusing to orphan outdated point {id!r}"
679
+ )
680
+ now = datetime.now(timezone.utc).isoformat()
681
+
682
+ proj.g.query(
683
+ "MATCH (n:Point {id:$id}) SET n.outdated = true, n.updatedAt = $now",
684
+ params={"id": id, "now": now},
685
+ )
686
+ proj.g.query(
687
+ "MATCH (a:Point {id:$new_id}), (b:Point {id:$old_id}) "
688
+ "MERGE (a)-[:CORRECTS]->(b)",
689
+ params={"new_id": corrected_by_id, "old_id": id},
690
+ )
691
+ # Dreaming (#85): invalidation changes the propagation graph.
692
+ self._mark_dirty([id, corrected_by_id])
693
+ return {"invalidated": True, "id": id, "corrected_by": corrected_by_id}
694
+
695
+ def supersede_point(self, old_id: str, new_id: str) -> dict:
696
+ """Atomically replace old Point with new — CORRECTS edge + outdated flag + edge transfer.
697
+
698
+ Transfers all edges from the old point to the new point:
699
+ - Operator edges (IMPL, NAND, hasPart) with idx
700
+ - Plain structural edges (aboutSubject, aboutObject, aboutAction,
701
+ aboutEvent, aboutPoint, aboutDocument, extractedFrom, etc.)
702
+ Preserves edge type and idx (source vs target position).
703
+ Leaves the old point outdated with only the CORRECTS edge from the new point.
704
+ """
705
+ from datetime import datetime, timezone
706
+ proj = self._get_proj()
707
+ now = datetime.now(timezone.utc).isoformat()
708
+
709
+ # 0. #329: collect + validate ALL edge types BEFORE any mutation.
710
+ # The edge types are interpolated into query structure (no params
711
+ # possible) — an unvalidated type (e.g. from a crafted edge) is a
712
+ # Cypher injection primitive AND would cause a partial transfer.
713
+ # Validation strictly precedes the outdated-flag/CORRECTS writes so
714
+ # a failure leaves the graph untouched.
715
+ edges_result = proj.g.query(
716
+ "MATCH (op:Point {is_operator:true})-[r]->(old:Point {id:$old_id}) "
717
+ "RETURN op.id, type(r), r.idx",
718
+ params={"old_id": old_id},
719
+ )
720
+ from .security import validate_rel_type
721
+ for row in edges_result.result_set:
722
+ validate_rel_type(row[1]) # raises ValueError before any mutation
723
+
724
+ # 1. Mark old outdated + create CORRECTS edge (same as invalidate)
725
+ proj.g.query(
726
+ "MATCH (n:Point {id:$id}) SET n.outdated = true, n.updatedAt = $now",
727
+ params={"id": old_id, "now": now},
728
+ )
729
+ proj.g.query(
730
+ "MATCH (a:Point {id:$new_id}), (b:Point {id:$old_id}) "
731
+ "MERGE (a)-[:CORRECTS]->(b)",
732
+ params={"new_id": new_id, "old_id": old_id},
733
+ )
734
+
735
+ # 2a. Transfer operator edges (IMPL, NAND, hasPart) — preserve provenance
736
+
737
+ transferred = 0
738
+ for row in edges_result.result_set:
739
+ op_id, edge_type, idx = row[0], row[1], row[2]
740
+ # Create new edge: operator → new point (same idx preserves source/target position)
741
+ proj.g.query(
742
+ f"MATCH (op:Point {{id:$op_id}}), (new:Point {{id:$new_id}}) "
743
+ f"CREATE (op)-[:{edge_type} {{idx:$idx}}]->(new)",
744
+ params={"op_id": op_id, "new_id": new_id, "idx": idx},
745
+ )
746
+ # Delete old edge (match by idx for precision)
747
+ proj.g.query(
748
+ f"MATCH (op:Point {{id:$op_id}})-[r:{edge_type} {{idx:$idx}}]->(old:Point {{id:$old_id}}) "
749
+ f"DELETE r",
750
+ params={"op_id": op_id, "idx": idx, "old_id": old_id},
751
+ )
752
+ transferred += 1
753
+
754
+ # 2b. Transfer plain structural edges (#122) — about*, extractedFrom, wasDerivedFrom, etc.
755
+ # These edges connect the Point to entities (Subject, Object, Source, etc.)
756
+ structural_rels = [
757
+ 'aboutSubject', 'aboutObject', 'aboutAction', 'aboutEvent',
758
+ 'aboutPoint', 'aboutDocument', 'extractedFrom', 'wasDerivedFrom'
759
+ ]
760
+ for rel in structural_rels:
761
+ struct_rows = proj.g.query(
762
+ f"MATCH (old:Point {{id:$old_id}})-[r:{rel}]->(target) "
763
+ f"RETURN id(target), target.id, labels(target)",
764
+ params={"old_id": old_id},
765
+ ).result_set
766
+ for row in struct_rows:
767
+ target_graph_id = row[0] # FalkorDB internal node id — exact match
768
+ # Create new edge: new point → same target (MERGE = idempotent, no dupes)
769
+ proj.g.query(
770
+ f"MATCH (new:Point {{id:$new_id}}), (t) WHERE id(t) = $tid "
771
+ f"MERGE (new)-[:{rel}]->(t)",
772
+ params={"new_id": new_id, "tid": target_graph_id},
773
+ )
774
+ # Delete old edge (match by exact internal node id)
775
+ proj.g.query(
776
+ f"MATCH (old:Point {{id:$old_id}})-[r:{rel}]->(t) WHERE id(t) = $tid "
777
+ f"DELETE r",
778
+ params={"old_id": old_id, "tid": target_graph_id},
779
+ )
780
+ transferred += 1
781
+
782
+ # Dreaming (#85): supersede changes the propagation graph around both.
783
+ self._mark_dirty([old_id, new_id])
784
+
785
+ return {
786
+ "invalidated": True,
787
+ "id": old_id,
788
+ "corrected_by": new_id,
789
+ "edges_transferred": transferred,
790
+ }
791
+
792
+ # ── Operators ─────────────────────────────────────────────────
793
+
794
+ def create_operator(self, op_type: str, source_id: str, target_ids: list[str],
795
+ label: str | None = None,
796
+ direction: str = "bidirectional") -> dict:
797
+ """Create an operator Point with optional semantic label.
798
+
799
+ Semantic-epistemic edge model (#7801):
800
+ - op_type: IMPL or NAND (epistemic mechanism)
801
+ - label: domain verb — "addresses", "hasPart", "opposes" (semantic layer)
802
+ - direction: "bidirectional" (default) or "unidirectional" — explicit flag
803
+ controlling EP back-propagation (ONTOLOGY v3.1 §3.1, §8).
804
+ - Operator carries the label and direction; IMPL/NAND edges carry confidence via EP.
805
+ """
806
+ if op_type not in ("IMPL", "NAND", "composedOf", "decomposesInto", "contains", "wraps"):
807
+ raise ValueError(
808
+ f"op_type must be 'IMPL', 'NAND', or a part/whole type, got {op_type!r}"
809
+ )
810
+ if direction not in ("bidirectional", "unidirectional"):
811
+ raise ValueError(
812
+ f"direction must be 'bidirectional' or 'unidirectional', got {direction!r}"
813
+ )
814
+ pid = ulid()
815
+ inputs = [source_id] + list(target_ids)
816
+ proj = self._get_proj()
817
+
818
+ # Validate all source/target Points exist (fail loudly, not silently)
819
+ existing = proj.g.query(
820
+ "MATCH (n:Point) WHERE n.id IN $ids RETURN n.id",
821
+ params={"ids": inputs},
822
+ ).result_set
823
+ existing_ids = {row[0] for row in existing}
824
+ missing = [i for i in inputs if i not in existing_ids]
825
+ if missing:
826
+ raise ValueError(f"Cannot create operator: Points {missing} do not exist")
827
+
828
+ # Build operator node with direction + optional label (context is NOT written — P1 #49)
829
+ extra_props = []
830
+ params = {"id": pid, "op": op_type, "direction": direction}
831
+ if label:
832
+ extra_props.append("label:$label")
833
+ params["label"] = label
834
+ props_clause = ", " + ", ".join(extra_props) if extra_props else ""
835
+ proj.g.query(
836
+ f"CREATE (o:Point {{id:$id, is_operator:true, op_type:$op, direction:$direction{props_clause}}})",
837
+ params=params,
838
+ )
839
+ # Ontology v2.1: map part/whole ops to hasPart, remove INPUT edges
840
+ edge_type = "hasPart" if op_type not in ("IMPL", "NAND") else op_type
841
+ for i, inp_id in enumerate(inputs):
842
+ proj.g.query(
843
+ f"MATCH (o:Point {{id:$oid}}), (s:Point {{id:$sid}}) "
844
+ f"CREATE (o)-[:{edge_type} {{idx:$i}}]->(s)",
845
+ params={"oid": pid, "sid": inp_id, "i": i},
846
+ )
847
+ # Draft → live lifecycle (#131): source point goes live when first edge created
848
+ proj.g.query(
849
+ "MATCH (s:Point {id:$sid}) SET s.status = 'live'",
850
+ params={"sid": source_id},
851
+ )
852
+ # Dreaming (#85): new edges change propagation — mark all inputs dirty.
853
+ self._mark_dirty(inputs)
854
+ result = self.get_point(pid)
855
+ return result
856
+
857
+ def annotate_operator(self, id: str, bias: float, precision: float,
858
+ consistency: float, directness: float) -> dict:
859
+ """Annotate an operator Point with structured epistemic dimensions.
860
+
861
+ Args:
862
+ id: Operator Point ID (must have is_operator=true).
863
+ bias: 0-1, how much hidden stake/additional interest beyond stated position.
864
+ precision: 0-1, how narrow/well-defined the relevance claim is.
865
+ consistency: 0-1, how stable this relevance is across contexts.
866
+ directness: 0-1, how directly the source bears on the target.
867
+
868
+ Raises ValueError if id not found, not an operator, or dims out of [0,1].
869
+ """
870
+ point = self.get_point(id)
871
+ if not point:
872
+ raise ValueError(f"Operator {id!r} not found")
873
+ if not point.get("is_operator"):
874
+ raise ValueError(f"Point {id!r} is not an operator")
875
+ for name, val in (("bias", bias), ("precision", precision),
876
+ ("consistency", consistency), ("directness", directness)):
877
+ if not 0 <= val <= 1:
878
+ raise ValueError(f"{name} must be 0-1, got {val}")
879
+ return self.update_point(id,
880
+ annotator_bias=bias, annotator_precision=precision,
881
+ annotator_consistency=consistency, annotator_directness=directness)
882
+
883
+ def mitigate_operator(self, id: str, reason: str, strength: float = 0.5) -> dict:
884
+ """Create a mitigation Point that modulates an operator's edge strength.
885
+
886
+ Args:
887
+ id: Operator Point ID to mitigate.
888
+ reason: Why the edge is weaker than it appears.
889
+ strength: 0-1, 0=fully neutralized, 1=fully intact (default 0.5).
890
+
891
+ Raises ValueError if id not found or not an operator.
892
+ Idempotent: second call updates existing mitigation (reason + strength),
893
+ does not create a duplicate.
894
+ """
895
+ if not 0 <= strength <= 1:
896
+ raise ValueError(f"strength must be 0-1, got {strength}")
897
+ point = self.get_point(id)
898
+ if not point:
899
+ raise ValueError(f"Operator {id!r} not found")
900
+ if not point.get("is_operator"):
901
+ raise ValueError(f"Point {id!r} is not an operator")
902
+ # Idempotency: check for existing mitigation
903
+ proj = self._get_proj()
904
+ existing = proj.g.query(
905
+ "MATCH (op:Point {id:$id})-[r:mitigated_by]->(m:Point) RETURN m.id",
906
+ params={"id": id},
907
+ ).result_set
908
+ if existing:
909
+ mid = existing[0][0]
910
+ return self.update_point(mid, content=f"[MITIGATION] {reason}",
911
+ mitigation_strength=strength)
912
+ # Create new mitigation Point
913
+ mid = ulid()
914
+ from datetime import datetime, timezone
915
+ now = datetime.now(timezone.utc).isoformat()
916
+ proj.g.query(
917
+ "CREATE (m:Point {id:$id, content:$c, pointKind:'statement', "
918
+ "mitigation_strength:$s, is_operator:false, createdAt:$now, updatedAt:$now})",
919
+ params={"id": mid, "c": f"[MITIGATION] {reason}", "s": strength, "now": now},
920
+ )
921
+ # Bidirectional link: mitigation Point -[:IMPL]-> operator, operator <-[:mitigated_by]- mitigation
922
+ proj.g.query(
923
+ "MATCH (m:Point {id:$mid}), (op:Point {id:$oid}) "
924
+ "CREATE (m)-[:IMPL]->(op), (op)-[:mitigated_by]->(m)",
925
+ params={"mid": mid, "oid": id},
926
+ )
927
+ # Dreaming (#85): new mitigation + IMPL edge change propagation.
928
+ self._mark_dirty([mid, id])
929
+ return self.get_point(mid)
930
+
931
+ # ── Query ─────────────────────────────────────────────────────
932
+
933
+ def query(self, kind: str | None = None,
934
+ **filters) -> list[dict]:
935
+ """Query points by pointKind and/or custom property filters.
936
+
937
+ For confidence-aware queries, use tortoise_fts_query() with query=None
938
+ for full-scan mode with EP annotation.
939
+ """
940
+ proj = self._get_proj()
941
+ clauses = ["(n.is_operator IS NULL OR n.is_operator = false)"]
942
+ params: dict[str, Any] = {}
943
+ if kind:
944
+ expanded = self._expand_kind(kind)
945
+ if len(expanded) == 1:
946
+ clauses.append("n.pointKind = $kind")
947
+ params["kind"] = expanded[0]
948
+ else:
949
+ placeholders = [f"$kind_{i}" for i in range(len(expanded))]
950
+ clauses.append(f"n.pointKind IN [{', '.join(placeholders)}]")
951
+ for i, k in enumerate(expanded):
952
+ params[f"kind_{i}"] = k
953
+ for key, val in filters.items():
954
+ # #329: strict ASCII identifier + reserved-key rejection (the old
955
+ # isalnum check allowed Unicode keys that broke Cypher params and
956
+ # filter keys colliding with kind/kind_N/skip/limit silently
957
+ # overwrote auto-generated parameters).
958
+ from .security import validate_filter_key
959
+ validate_filter_key(key)
960
+ clauses.append(f"n.`{key}` = ${key}")
961
+ params[key] = val
962
+ where = " AND ".join(clauses)
963
+ rows = proj.g.query(
964
+ f"MATCH (n:Point) WHERE {where} RETURN properties(n)",
965
+ params=params,
966
+ ).result_set
967
+ return [r[0] for r in rows]
968
+
969
+ def paginated_query(self, kind: str | None = None,
970
+ skip: int = 0, limit: int = 20, **filters) -> dict:
971
+ """Query points with pagination. Returns {results, total, hasMore}.
972
+ """
973
+ proj = self._get_proj()
974
+ clauses = ["(n.is_operator IS NULL OR n.is_operator = false)"]
975
+ params: dict[str, Any] = {}
976
+ if kind:
977
+ expanded = self._expand_kind(kind)
978
+ if len(expanded) == 1:
979
+ clauses.append("n.pointKind = $kind")
980
+ params["kind"] = expanded[0]
981
+ else:
982
+ placeholders = [f"$kind_{i}" for i in range(len(expanded))]
983
+ clauses.append(f"n.pointKind IN [{', '.join(placeholders)}]")
984
+ for i, k in enumerate(expanded):
985
+ params[f"kind_{i}"] = k
986
+ for key, val in filters.items():
987
+ # #329: strict ASCII identifier + reserved-key rejection (the old
988
+ # isalnum check allowed Unicode keys that broke Cypher params and
989
+ # filter keys colliding with kind/kind_N/skip/limit silently
990
+ # overwrote auto-generated parameters).
991
+ from .security import validate_filter_key
992
+ validate_filter_key(key)
993
+ clauses.append(f"n.`{key}` = ${key}")
994
+ params[key] = val
995
+ where = " AND ".join(clauses)
996
+ total = proj.g.query(
997
+ f"MATCH (n:Point) WHERE {where} RETURN count(n)",
998
+ params=params,
999
+ ).result_set[0][0]
1000
+ rows = proj.g.query(
1001
+ f"MATCH (n:Point) WHERE {where} RETURN properties(n)"
1002
+ f" ORDER BY n.createdAt DESC SKIP $skip LIMIT $limit",
1003
+ params={**params, "skip": skip, "limit": limit},
1004
+ ).result_set
1005
+ results = [r[0] for r in rows]
1006
+
1007
+ return {"results": results, "total": total, "hasMore": skip + limit < total}
1008
+
1009
+ def get_point(self, id: str) -> dict:
1010
+ """Get a Point by ID. Returns dict of all properties, or {} if not found."""
1011
+ proj = self._get_proj()
1012
+ rows = proj.g.query(
1013
+ "MATCH (n:Point {id:$id}) RETURN properties(n)",
1014
+ params={"id": id},
1015
+ ).result_set
1016
+ return rows[0][0] if rows else {}
1017
+
1018
+ def traverse(self, id: str, relationship_type: str, direction: str = "outgoing") -> list[dict]:
1019
+ """Traverse relationships from a Point. Returns connected point dicts.
1020
+
1021
+ #329: relationship_type is allowlisted (KNOWN_REL_TYPES) — it is
1022
+ interpolated into the query STRUCTURE (``-[:TYPE]->``) where
1023
+ parameterization is impossible; an unvalidated value is a Cypher
1024
+ injection primitive. direction is validated to outgoing/incoming.
1025
+ """
1026
+ proj = self._get_proj()
1027
+ # #329: validate before building any Cypher
1028
+ from .security import validate_rel_type
1029
+ validate_rel_type(relationship_type)
1030
+ if direction not in ("outgoing", "incoming"):
1031
+ raise ValueError(f"Invalid direction: {direction!r}. Use 'outgoing' or 'incoming'.")
1032
+ pat = (f"(n:Point {{id:$id}})-[:{relationship_type}]->(m:Point)"
1033
+ if direction == "outgoing" else
1034
+ f"(n:Point {{id:$id}})<-[:{relationship_type}]-(m:Point)")
1035
+ rows = proj.g.query(
1036
+ f"MATCH {pat} RETURN m.id, m.content, m.pointKind",
1037
+ params={"id": id},
1038
+ ).result_set
1039
+ return [
1040
+ {"id": r[0], "content": r[1], "pointKind": r[2]}
1041
+ for r in rows
1042
+ ]
1043
+
1044
+ # ── Chain Integrity ───────────────────────────────────────────
1045
+
1046
+ def check_structure(self) -> list[dict]:
1047
+ """Check Gate 0→4 chain integrity. Uses pack-aware kind expansion."""
1048
+ proj = self._get_proj()
1049
+ violations: list[dict] = []
1050
+
1051
+ # Resolve kinds via pack registry (handles namespace prefixes)
1052
+ uc_kind = self._expand_kind("useCase")
1053
+ jtbd_kind = self._expand_kind("jobToBeDone")
1054
+ uj_kind = self._expand_kind("userJourney")
1055
+ wf_kind = self._expand_kind("workflow")
1056
+ req_kind = self._expand_kind("requirement")
1057
+
1058
+ # Build IN clauses
1059
+ def kind_in(kinds):
1060
+ return ", ".join(f"'{k}'" for k in kinds)
1061
+
1062
+ # useCase without parent JTBD
1063
+ ucs = proj.g.query(
1064
+ f"MATCH (uc:Point) WHERE uc.pointKind IN [{kind_in(uc_kind)}] RETURN uc.id, uc.uc_id"
1065
+ ).result_set
1066
+ for uc_id, uc_ref in ucs:
1067
+ parents = proj.g.query(
1068
+ f"MATCH (op:Point {{is_operator:true, op_type:'composedOf'}})"
1069
+ f"-[:hasPart]->(uc:Point {{id:$id}}), "
1070
+ f"(op)-[:hasPart]->(jtbd:Point) WHERE jtbd.pointKind IN [{kind_in(jtbd_kind)}] "
1071
+ f"RETURN jtbd.id",
1072
+ params={"id": uc_id},
1073
+ ).result_set
1074
+ if not parents:
1075
+ violations.append({
1076
+ "type": "orphan_use_case",
1077
+ "id": uc_id,
1078
+ "message": f"useCase {uc_ref or uc_id} has no parent JTBD",
1079
+ })
1080
+
1081
+ # userJourney dangling UC refs
1082
+ for uj_id, covered in proj.g.query(
1083
+ f"MATCH (uj:Point) WHERE uj.pointKind IN [{kind_in(uj_kind)}] RETURN uj.id, uj.covered_use_cases"
1084
+ ).result_set:
1085
+ if not covered:
1086
+ continue
1087
+ for uc_ref in covered.split(","):
1088
+ uc_ref = uc_ref.strip()
1089
+ if not proj.g.query(
1090
+ f"MATCH (uc:Point) WHERE uc.pointKind IN [{kind_in(uc_kind)}] AND uc.uc_id=$ref RETURN count(uc) > 0",
1091
+ params={"ref": uc_ref},
1092
+ ).result_set[0][0]:
1093
+ violations.append({
1094
+ "type": "dangling_use_case_ref",
1095
+ "id": uj_id,
1096
+ "message": f"userJourney {uj_id} refs non-existent useCase {uc_ref}",
1097
+ })
1098
+
1099
+ # Workflow dangling JTBD refs
1100
+ for wf_id, enables in proj.g.query(
1101
+ f"MATCH (wf:Point) WHERE wf.pointKind IN [{kind_in(wf_kind)}] RETURN wf.id, wf.enables_jtbd"
1102
+ ).result_set:
1103
+ if not enables:
1104
+ continue
1105
+ for jtbd_ref in enables.split(","):
1106
+ jtbd_ref = jtbd_ref.strip()
1107
+ if not proj.g.query(
1108
+ f"MATCH (j:Point) WHERE j.pointKind IN [{kind_in(jtbd_kind)}] AND j.jtbd_id=$ref RETURN count(j) > 0",
1109
+ params={"ref": jtbd_ref},
1110
+ ).result_set[0][0]:
1111
+ violations.append({
1112
+ "type": "dangling_jtbd_ref",
1113
+ "id": wf_id,
1114
+ "message": f"workflow {wf_id} refs non-existent JTBD {jtbd_ref}",
1115
+ })
1116
+
1117
+ # Requirement dangling Workflow refs
1118
+ for req_id, wf_ref in proj.g.query(
1119
+ f"MATCH (req:Point) WHERE req.pointKind IN [{kind_in(req_kind)}] RETURN req.id, req.enabled_workflow"
1120
+ ).result_set:
1121
+ if not wf_ref or wf_ref == "ALL":
1122
+ continue
1123
+ if not proj.g.query(
1124
+ f"MATCH (w:Point) WHERE w.pointKind IN [{kind_in(wf_kind)}] AND w.wf_id=$ref RETURN count(w) > 0",
1125
+ params={"ref": wf_ref},
1126
+ ).result_set[0][0]:
1127
+ violations.append({
1128
+ "type": "dangling_workflow_ref",
1129
+ "id": req_id,
1130
+ "message": f"requirement {req_id} refs non-existent workflow {wf_ref}",
1131
+ })
1132
+
1133
+ # Orphaned draft points — created but never wired (#131)
1134
+ for row in proj.g.query(
1135
+ "MATCH (n:Point {status:'draft'}) "
1136
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
1137
+ "AND NOT (n)--() "
1138
+ "RETURN n.id, n.content, n.pointKind, n.createdAt "
1139
+ "ORDER BY n.createdAt"
1140
+ ).result_set:
1141
+ violations.append({
1142
+ "type": "orphaned_draft",
1143
+ "id": row[0],
1144
+ "message": (
1145
+ f"Draft point '{row[1][:80] if row[1] else ''}' "
1146
+ f"of kind '{row[2] or 'unknown'}' has no edges "
1147
+ f"(created {row[3] or 'unknown'})"
1148
+ ),
1149
+ })
1150
+
1151
+ return violations
1152
+
1153
+ def summarize_structure(self) -> dict:
1154
+ """Count points per Gate (by pointKind). Returns {gate: count, ..., total}.
1155
+
1156
+ P1 #49: re-keyed from context strings (tortoise-wf-gate0..4) to pointKind
1157
+ (jobToBeDone, useCase, userJourney, workflow, requirement). Pre-existing
1158
+ experimental points that had context but no matching pointKind may show 0
1159
+ — expected under the #49 re-home (pointKind is the target vocabulary).
1160
+ """
1161
+ proj = self._get_proj()
1162
+ gates = [
1163
+ ("gate0_jtbds", "jobToBeDone"),
1164
+ ("gate1_use_cases", "useCase"),
1165
+ ("gate2_user_journeys", "userJourney"),
1166
+ ("gate3_workflows", "workflow"),
1167
+ ("gate4_requirements", "requirement"),
1168
+ ]
1169
+ result: dict[str, int] = {}
1170
+ for key, kind in gates:
1171
+ result[key] = proj.g.query(
1172
+ "MATCH (n:Point {pointKind:$k}) "
1173
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
1174
+ "RETURN count(n)",
1175
+ params={"k": kind},
1176
+ ).result_set[0][0]
1177
+ result["total"] = sum(result.values())
1178
+ return result
1179
+
1180
+ # ── Taxonomy ─────────────────────────────────────────────────
1181
+
1182
+ def taxonomy(self) -> dict[str, int]:
1183
+ """Count entities by node label. Returns {Point: N, Event: N, ...}."""
1184
+ from .taxonomy import taxonomy as _taxonomy
1185
+ return _taxonomy(self._get_proj())
1186
+
1187
+ def list_pointkinds(self) -> list[dict]:
1188
+ """All pointKinds present in the graph with counts. Returns [{kind, count, pack}]."""
1189
+ proj = self._get_proj()
1190
+ rows = proj.g.query(
1191
+ "MATCH (n:Point) "
1192
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
1193
+ "AND n.pointKind IS NOT NULL "
1194
+ "RETURN n.pointKind, count(n) ORDER BY count(n) DESC"
1195
+ ).result_set
1196
+ result: list[dict] = []
1197
+ for row in rows:
1198
+ kind = row[0]
1199
+ count = row[1]
1200
+ pack = kind.split(":", 1)[0] if ":" in kind else ""
1201
+ result.append({"kind": kind, "count": count, "pack": pack})
1202
+ return result
1203
+
1204
+ def list_sources(self) -> list[dict]:
1205
+ """All Sources with point counts. Returns [{url, sourceKind, points}]."""
1206
+ proj = self._get_proj()
1207
+ rows = proj.g.query(
1208
+ "MATCH (s:Source) "
1209
+ "OPTIONAL MATCH (p:Point)-[:extractedFrom]->(s) "
1210
+ "RETURN s.url, s.sourceKind, count(p) AS points "
1211
+ "ORDER BY points DESC"
1212
+ ).result_set
1213
+ return [
1214
+ {"url": row[0], "sourceKind": row[1], "points": row[2]}
1215
+ for row in rows
1216
+ ]
1217
+
1218
+ def list_tags(self) -> list[dict]:
1219
+ """All Tag names with count of tagged Points. Returns [{name, count}].
1220
+
1221
+ Orphaned :Tag nodes (no TAGGED edges) are garbage-collected when
1222
+ edges are removed (update_point tag sync + delete_point, #485), so
1223
+ count 0 entries should not normally appear.
1224
+ """
1225
+ proj = self._get_proj()
1226
+ rows = proj.g.query(
1227
+ "MATCH (t:Tag) "
1228
+ "OPTIONAL MATCH (p:Point)-[:TAGGED]->(t) "
1229
+ "RETURN t.name AS name, count(p) AS count "
1230
+ "ORDER BY name"
1231
+ ).result_set
1232
+ return [{"name": row[0], "count": row[1]} for row in rows]
1233
+
1234
+ def query_points_by_tag(self, tag: str) -> list[dict]:
1235
+ """Return Points connected via TAGGED edge to the given Tag name."""
1236
+ proj = self._get_proj()
1237
+ rows = proj.g.query(
1238
+ "MATCH (p:Point)-[:TAGGED]->(t:Tag {name:$tag}) "
1239
+ "RETURN properties(p) "
1240
+ "ORDER BY p.createdAt DESC",
1241
+ params={"tag": tag},
1242
+ ).result_set
1243
+ return [r[0] for r in rows]
1244
+
1245
+ def list_namespaces(self) -> list[dict]:
1246
+ """Installed pack namespaces with kind counts. Returns [{namespace, name, kind_count}]."""
1247
+ registry = _get_kind_expander()
1248
+ packs = registry.list_packs()
1249
+ return [
1250
+ {
1251
+ "namespace": p["namespace"],
1252
+ "name": p["name"],
1253
+ "kind_count": sum(p["kind_counts"].values()),
1254
+ }
1255
+ for p in packs
1256
+ ]
1257
+
1258
+ def list_topics(self, entity_id: str) -> dict:
1259
+ """entityProfile lite for an entity. Returns {id, pointKind, context, neighbors, neighborCounts}."""
1260
+ from .taxonomy import list_topics as _list_topics
1261
+ return _list_topics(self._get_proj(), entity_id)
1262
+
1263
+ # ── Bulk ──────────────────────────────────────────────────────
1264
+
1265
+ def batch_create_points(self, points_list: list[dict]) -> list[dict]:
1266
+ """Create multiple points. Each dict needs {kind, content, **props}."""
1267
+ return [self.create_point(**p) for p in points_list]
1268
+
1269
+ def file_decision(self, options: list[str], evidence: list[str],
1270
+ choice: int) -> dict:
1271
+ """File a simple decision directly to the graph — no EP, no calibration,
1272
+ no research cycles. Creates decision + options + evidence + IMPL edges
1273
+ atomically. For low-stakes decisions where the answer is clear (#133).
1274
+
1275
+ Args:
1276
+ options: list of option descriptions (e.g. ["JSON", "YAML"])
1277
+ evidence: list of evidence statements supporting the choice
1278
+ choice: 0-indexed index into options (the chosen option)
1279
+
1280
+ Returns {decision_id, option_ids: [...], evidence_ids: [...]}.
1281
+ """
1282
+ if not options:
1283
+ raise ValueError("At least one option required")
1284
+ if choice < 0 or choice >= len(options):
1285
+ raise ValueError(f"choice={choice} out of range [0, {len(options)-1}]")
1286
+
1287
+ # 1. Create decision point
1288
+ decision = self.create_point(
1289
+ "decision",
1290
+ f"Decision: {options[choice]}",
1291
+ status="live",
1292
+ )
1293
+ decision_id = decision["id"]
1294
+
1295
+ # 2. Create option points + IMPL edges from decision
1296
+ option_ids = []
1297
+ for i, opt in enumerate(options):
1298
+ opt_point = self.create_point(
1299
+ "option",
1300
+ f"Option {i+1}: {opt}",
1301
+ status="live", # options are targets, not sources — explicit live
1302
+ )
1303
+ option_ids.append(opt_point["id"])
1304
+ # IMPL edge: decision -> option ("decision considers option")
1305
+ self.create_operator("IMPL", decision_id, [opt_point["id"]])
1306
+
1307
+ # 3. Create evidence points + IMPL edges to the chosen option
1308
+ evidence_ids = []
1309
+ chosen_id = option_ids[choice]
1310
+ for ev in evidence:
1311
+ ev_point = self.create_point(
1312
+ "evidence",
1313
+ ev,
1314
+ )
1315
+ evidence_ids.append(ev_point["id"])
1316
+ # IMPL edge: evidence -> chosen option ("evidence supports choice")
1317
+ self.create_operator("IMPL", ev_point["id"], [chosen_id])
1318
+
1319
+ return {
1320
+ "decision_id": decision_id,
1321
+ "option_ids": option_ids,
1322
+ "evidence_ids": evidence_ids,
1323
+ }
1324
+
1325
+ def file_human_approval(self, approver_id: str, artifact_id: str,
1326
+ point_ids: list[str],
1327
+ decision_content: str | None = None) -> dict:
1328
+ """Record a human approval of a planning artifact (#531).
1329
+
1330
+ Canonical approval pattern (research #421): an Event
1331
+ (eventKind: ``humanApproval``) records the occurrence with full
1332
+ provenance — approver Subject, artifact, approved claim Points — while
1333
+ a decision Point (pointKind: ``humanApproval``) carries the epistemic
1334
+ weight: it seeds the grounding a-vector and receives an EP evidence
1335
+ prior so dependent claims strengthen. Unidirectional IMPL fan-out
1336
+ (label ``approvedBy``) links the approval Point to each approved claim
1337
+ Point — deliberately unidirectional so EP never propagates claim
1338
+ weakness back into the approval.
1339
+
1340
+ Deliberately NOT stored: no ``approved`` status flag on the artifact —
1341
+ approval is derived from the event stream at query time (ONTOLOGY §2).
1342
+
1343
+ Args:
1344
+ approver_id: Subject id (or name) of the human approving.
1345
+ artifact_id: Object/Document id (or name) of the artifact approved.
1346
+ point_ids: claim Point ids the approval covers (non-operator).
1347
+ decision_content: optional content override for the decision Point
1348
+ (default ``"Approved: <artifact>"``).
1349
+
1350
+ Returns {event_id, decision_point_id, impl_operator_ids,
1351
+ confidence_delta} where confidence_delta maps each approved
1352
+ claim id to its confidence change after the EP run.
1353
+ """
1354
+ from datetime import datetime, timezone
1355
+ proj = self._get_proj()
1356
+
1357
+ # 1. Validate approver Subject exists (fail loudly, not silently)
1358
+ r = proj.g.query(
1359
+ "MATCH (s:Subject) WHERE s.id = $id OR s.name = $id RETURN s.id",
1360
+ params={"id": approver_id},
1361
+ ).result_set
1362
+ if not r:
1363
+ raise ValueError(
1364
+ f"Cannot file human approval: Subject {approver_id!r} does not exist"
1365
+ )
1366
+
1367
+ # 2. Validate artifact exists (Object or Document)
1368
+ r = proj.g.query(
1369
+ "MATCH (n) WHERE (n:Object OR n:Document) "
1370
+ "AND (n.id = $id OR n.name = $id) RETURN labels(n), n.id",
1371
+ params={"id": artifact_id},
1372
+ ).result_set
1373
+ if not r:
1374
+ raise ValueError(
1375
+ f"Cannot file human approval: artifact {artifact_id!r} does not exist"
1376
+ )
1377
+
1378
+ # 3. Validate point_ids exist and are non-operator Points
1379
+ if not point_ids:
1380
+ raise ValueError("Cannot file human approval: at least one claim Point required")
1381
+ r = proj.g.query(
1382
+ "MATCH (n:Point) WHERE n.id IN $ids "
1383
+ "AND (n.is_operator IS NULL OR n.is_operator = false) RETURN n.id",
1384
+ params={"ids": point_ids},
1385
+ ).result_set
1386
+ existing = {row[0] for row in r}
1387
+ missing = [pid for pid in point_ids if pid not in existing]
1388
+ if missing:
1389
+ raise ValueError(
1390
+ f"Cannot file human approval: Points {missing} do not exist or are operators"
1391
+ )
1392
+
1393
+ now = datetime.now(timezone.utc).isoformat()
1394
+
1395
+ # 4. Decision Point (pointKind humanApproval) — epistemic weight carrier
1396
+ content = decision_content or f"Approved: {artifact_id}"
1397
+ decision = self.create_point(
1398
+ "humanApproval",
1399
+ content,
1400
+ status="live",
1401
+ authoredBy=approver_id,
1402
+ )
1403
+ decision_id = decision["id"]
1404
+
1405
+ # 5. Event (eventKind humanApproval) — the occurrence record
1406
+ event = self.create_event(
1407
+ name=f"human approval of {artifact_id}",
1408
+ eventKind="humanApproval",
1409
+ startedAt=now,
1410
+ eventStatus="completed",
1411
+ )
1412
+ event_id = event["eventId"]
1413
+ # Wire provenance: approver performs; uses artifact; aboutPoint each
1414
+ # approved claim; produces the decision Point (design #421).
1415
+ proj.create_edge(approver_id, event_id, "performs")
1416
+ proj.create_edge(event_id, artifact_id, "uses")
1417
+ for pid in point_ids:
1418
+ proj.create_about_edge(event_id, pid, "aboutPoint")
1419
+ proj.create_edge(event_id, decision_id, "produces")
1420
+
1421
+ # 6. Unidirectional IMPL fan-out: approval → each approved claim.
1422
+ # create_operator defaults to bidirectional — direction must be
1423
+ # explicit so EP never back-propagates claim weakness into the
1424
+ # approval point.
1425
+ op = self.create_operator(
1426
+ "IMPL", decision_id, point_ids,
1427
+ label="approvedBy", direction="unidirectional",
1428
+ )
1429
+
1430
+ # 7. EP with evidence prior on the approval Point: Beta(10,1) is a
1431
+ # strong positive prior — dependents strengthen (issue #531).
1432
+ before = {}
1433
+ for pid in point_ids:
1434
+ p = self.get_point(pid)
1435
+ before[pid] = p.get("confidence", 0.5) if p else 0.5
1436
+ self.compute_confidence(evidence={decision_id: (10, 1)})
1437
+ deltas = {}
1438
+ for pid in point_ids:
1439
+ p = self.get_point(pid)
1440
+ after = p.get("confidence", 0.5) if p else 0.5
1441
+ deltas[pid] = round(after - before[pid], 4)
1442
+
1443
+ # 8. Approval seeds the grounding a-vector — re-compute (api.py pattern)
1444
+ if hasattr(proj, "compute_grounding"):
1445
+ proj.compute_grounding()
1446
+
1447
+ return {
1448
+ "event_id": event_id,
1449
+ "decision_point_id": decision_id,
1450
+ "impl_operator_ids": [op["id"]],
1451
+ "confidence_delta": deltas,
1452
+ }
1453
+
1454
+ # ── Lifecycle ─────────────────────────────────────────────────
1455
+
1456
+ def list_graphs(self) -> list[str]:
1457
+ """List all graph names in the database."""
1458
+ return self._get_proj().list_graphs()
1459
+
1460
+ def _audit(self, team_id: str, actor_user_id: str | None,
1461
+ operation: str, **kwargs) -> None:
1462
+ """Log an audit event. No-op if audit logger not initialized."""
1463
+ if self._audit_logger is None:
1464
+ from .audit_events import AuditLogger
1465
+ self._audit_logger = AuditLogger()
1466
+ self._audit_logger.append(
1467
+ team_id=team_id,
1468
+ actor_user_id=actor_user_id,
1469
+ operation=operation,
1470
+ **kwargs,
1471
+ )
1472
+
1473
+ def list_relations(self) -> list[dict]:
1474
+ """List all relation declarations across installed packs.
1475
+
1476
+ Returns [{"pack": ..., "predicate": ..., "fromKind": ..., "toKind": ...,
1477
+ "mechanism": ...}]. Pack relations describe valid edge types between
1478
+ entity kinds — use for schema discovery.
1479
+ """
1480
+ return _get_kind_expander().list_relations()
1481
+
1482
+ def close(self) -> None:
1483
+ """Close the underlying database connection and audit logger."""
1484
+ if self._audit_logger is not None:
1485
+ self._audit_logger.close()
1486
+ self._audit_logger = None
1487
+ if self._proj is not None:
1488
+ self._proj.close()
1489
+ self._proj = None
1490
+ self._registry_g = None
1491
+
1492
+ # ── P1-4: Entity Linking ────────────────────────────────────
1493
+
1494
+ def provenance(self, point_id: str) -> dict:
1495
+ """Provenance chain — "Who decided this?" Point → Subject → delegation."""
1496
+ point = self.get_point(point_id)
1497
+ if not point:
1498
+ return {"error": f"Point {point_id} not found"}
1499
+ author = point.get("authoredBy", "")
1500
+ chain = {"point": {"id": point_id, "content": (point.get("content") or "")[:200],
1501
+ "authoredBy": author}}
1502
+ if not author:
1503
+ return chain
1504
+ proj = self._get_proj()
1505
+ rows = proj.g.query(
1506
+ "MATCH (s:Subject) WHERE toLower(s.name) = toLower($n) RETURN properties(s)",
1507
+ params={"n": author},
1508
+ ).result_set
1509
+ if not rows:
1510
+ return {**chain, "subject": None}
1511
+ sub = rows[0][0]
1512
+ chain["subject"] = {"id": sub.get("id"), "name": sub.get("name"),
1513
+ "kind": sub.get("subjectKind", "")}
1514
+ # ponytail: follow outgoing rels for Role → Team delegation
1515
+ rels = proj.g.query(
1516
+ "MATCH (s:Subject {id:$sid})-[r]->(n) RETURN type(r), labels(n)[0], properties(n)",
1517
+ params={"sid": sub["id"]},
1518
+ ).result_set
1519
+ chain["delegation"] = [{"via": r[0], "node_type": r[1], "props": r[2]} for r in rels]
1520
+ return chain
1521
+
1522
+ # ── #7045: about edges backfill (Ontology v2.1) ──────────
1523
+
1524
+ def backfill_about_entities(self) -> dict:
1525
+ """Keyword-match Points against Subject/Object/Event/Document names → about edges.
1526
+
1527
+ For each Point (non-operator), checks if its content contains any Subject,
1528
+ Object, Event, or Document name/title. If yes, creates the matching about*
1529
+ edge (aboutSubject, aboutObject, aboutEvent, aboutDocument).
1530
+ Idempotent — MERGE prevents duplicates.
1531
+
1532
+ Returns {scanned, updated, entities_matched}.
1533
+ """
1534
+ proj = self._get_proj()
1535
+ # Load all entity names → ids (flat dict for membership check)
1536
+ entities: dict[str, str] = {}
1537
+ # Subject + Object: matched by name property
1538
+ for label in ("Subject", "Object"):
1539
+ rows = proj.g.query(
1540
+ f"MATCH (e:{label}) WHERE e.name IS NOT NULL RETURN e.name, e.id"
1541
+ ).result_set
1542
+ for name, eid in rows:
1543
+ if name:
1544
+ entities[name.lower()] = eid
1545
+ # Event: matched by name property (set by create_event)
1546
+ for row in proj.g.query(
1547
+ "MATCH (e:Event) WHERE e.name IS NOT NULL RETURN e.name, e.eventId"
1548
+ ).result_set:
1549
+ name, eid = row[0], row[1]
1550
+ if name:
1551
+ entities[name.lower()] = eid
1552
+ # Document: matched by title (primary display name) or name
1553
+ for row in proj.g.query(
1554
+ "MATCH (d:Document) WHERE d.title IS NOT NULL RETURN d.title, d.id"
1555
+ ).result_set:
1556
+ title, did = row[0], row[1]
1557
+ if title:
1558
+ entities[title.lower()] = did
1559
+
1560
+ # Ontology v2.1: use per-type about* edges instead of property
1561
+ rows = proj.g.query(
1562
+ "MATCH (n:Point) "
1563
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
1564
+ "RETURN n.id, n.content"
1565
+ ).result_set
1566
+
1567
+ scanned, updated, matched = 0, 0, 0
1568
+ for pid, content in rows:
1569
+ scanned += 1
1570
+ if not content:
1571
+ continue
1572
+ content_lower = content.lower()
1573
+ for name, eid in entities.items():
1574
+ if name in content_lower:
1575
+ proj._create_about_edges(pid, name)
1576
+ matched += 1
1577
+ if matched > 0:
1578
+ updated += 1
1579
+
1580
+ return {"scanned": scanned, "updated": updated, "entities_matched": matched}
1581
+
1582
+ # ── P1-3: Staleness ─────────────────────────────────────────
1583
+
1584
+ def stale_points(self, days: int = 30, limit: int = 50) -> dict:
1585
+ """Return Points not updated in N days. Returns {stale: [...], count: N, cutoff: '...'}."""
1586
+ proj = self._get_proj()
1587
+ stale = proj.stale_points(days=days, limit=limit)
1588
+ return {"stale": stale, "count": len(stale),
1589
+ "cutoff": f"{days} days", "limit": limit}
1590
+
1591
+ # ── EP Belief Propagation (#6908) ────────────────────────────
1592
+
1593
+ def _get_ep(self):
1594
+ if self._ep is None:
1595
+ from .ep import TortoiseEP
1596
+ self._ep = TortoiseEP(self._get_proj())
1597
+ return self._ep
1598
+
1599
+ # ── Dreaming (#85) ──────────────────────────────────────────────
1600
+
1601
+ def _get_dreamer(self):
1602
+ """Lazy-init the Dreamer (thread-safe)."""
1603
+ if self._dreamer is None:
1604
+ from .dream import Dreamer
1605
+ self._dreamer = Dreamer(self)
1606
+ return self._dreamer
1607
+
1608
+ def _mark_dirty(self, point_ids: list[str]) -> None:
1609
+ """Mark claims whose confidence is now stale after a write.
1610
+
1611
+ 1-hop reverse BFS (#85 contract): from the mutated point, collect the
1612
+ operators that target it, then the claims those operators target.
1613
+ The dream expands to max_hops=2 for full propagation — do not reduce
1614
+ the dream's max_hops below 2 without expanding this marking.
1615
+ """
1616
+ if not point_ids:
1617
+ return
1618
+ # The mutated points themselves are always dirty (their baseline
1619
+ # priors / properties changed).
1620
+ self._dirty_roots.update(point_ids)
1621
+ proj = self._get_proj()
1622
+ # Operators targeting the mutated points (reverse of operator→point).
1623
+ rows = proj.g.query(
1624
+ "MATCH (op:Point {is_operator:true})-[:IMPL|NAND]->(p:Point) "
1625
+ "WHERE p.id IN $ids RETURN DISTINCT op.id",
1626
+ params={"ids": list(point_ids)},
1627
+ ).result_set
1628
+ op_ids = [r[0] for r in rows]
1629
+ if not op_ids:
1630
+ return
1631
+ # Claims those operators target (1-hop forward from operators).
1632
+ rows = proj.g.query(
1633
+ "MATCH (op:Point {is_operator:true})-[:IMPL|NAND]->(c:Point) "
1634
+ "WHERE op.id IN $oids RETURN DISTINCT c.id",
1635
+ params={"oids": op_ids},
1636
+ ).result_set
1637
+ self._dirty_roots.update(r[0] for r in rows)
1638
+
1639
+ def dream(self, dirty_only: bool = True, full: bool = False,
1640
+ max_hops: int = 2) -> dict:
1641
+ """Run EP stabilization (#85).
1642
+
1643
+ Args:
1644
+ dirty_only: dream the accumulated dirty roots (default True).
1645
+ full: whole-graph stabilization (dream_all). Mutually exclusive
1646
+ with dirty_only + anchors.
1647
+ max_hops: EP subgraph expansion (keep ≥2 — contract with
1648
+ _mark_dirty).
1649
+
1650
+ Returns {iterations, converged, affected_claims} or the dream_all
1651
+ summary for full=True.
1652
+ """
1653
+ dreamer = self._get_dreamer()
1654
+ if full:
1655
+ return dreamer.dream_all(max_hops=max_hops)
1656
+ if not dirty_only and not self._dirty_roots:
1657
+ return {"iterations": 0, "converged": True, "affected_claims": []}
1658
+ anchors = list(self._dirty_roots)
1659
+ result = dreamer.dream(anchors, max_hops=max_hops)
1660
+ # Clear dirty roots that converged (keep any that failed to converge
1661
+ # so a later dream retries them).
1662
+ if result.get("converged", False):
1663
+ self._dirty_roots.clear()
1664
+ else:
1665
+ affected = set(result.get("affected_claims", []))
1666
+ self._dirty_roots -= affected
1667
+ return result
1668
+
1669
+ def _select_subgraph(self, anchors: list[str], max_hops: int = 1,
1670
+ rel_filter: str = "IMPL|NAND",
1671
+ direction: str = "both") -> list[str]:
1672
+ """BFS subgraph selection from anchor Points to collect operator IDs.
1673
+
1674
+ Delegates to the shared _bfs_select_operators in tortoise.analyze.
1675
+ """
1676
+ from .analyze import _bfs_select_operators
1677
+ proj = self._get_proj()
1678
+ result = _bfs_select_operators(proj, anchors, max_hops=max_hops,
1679
+ rel_filter=rel_filter, direction=direction)
1680
+ return list(result)
1681
+
1682
+ def compute_confidence(self, factors=None, evidence=None,
1683
+ anchors: list[str] | None = None,
1684
+ max_hops: int = 1,
1685
+ rel_filter: str = "IMPL|NAND",
1686
+ direction: str = "both",
1687
+ require_calibration: bool = False,
1688
+ recency_decay: float | None = None) -> dict:
1689
+ """Compute confidence via EP belief propagation. Returns {iterations, converged, confidences}.
1690
+
1691
+ Args:
1692
+ factors: operator IDs (list[str]) or factor tuples. If None, auto-extracts.
1693
+ evidence: optional {claim_id: (alpha, beta)} priors.
1694
+ anchors: list of Point IDs for BFS subgraph selection.
1695
+ max_hops: BFS expansion depth when using anchors (default 1).
1696
+ rel_filter: edge types for BFS — "IMPL", "NAND", or "IMPL|NAND" (default).
1697
+ direction: IMPL edge traversal direction — "incoming", "outgoing", or "both" (default).
1698
+ require_calibration: if True, raises CalibrationError when evidence points are uncalibrated.
1699
+ recency_decay: optional recency decay factor (default 0.95 from TORTOISE_EP_RECENCY_DECAY).
1700
+ T0 sources exempt; lower tiers get gentle decay. 1.0 = no decay.
1701
+
1702
+ Precedence: factors > anchors > auto-extract-all.
1703
+ """
1704
+ proj = self._get_proj()
1705
+ ep = self._get_ep()
1706
+ # Hydrate evidence from graph-persisted baselines (survives SDK restarts)
1707
+ self._hydrate_evidence()
1708
+ # Apply source-based credibility inheritance (with recency modulation #122)
1709
+ self._apply_source_inheritance(recency_decay=recency_decay)
1710
+ if evidence:
1711
+ self._evidence.update(evidence)
1712
+ # Calibration gate
1713
+ if require_calibration:
1714
+ from .exceptions import CalibrationError
1715
+ summary = self.calibrate_summary()
1716
+ evidence_kinds = {"statement", "observation", "hypothesis"}
1717
+ uncalibrated = [
1718
+ s for s in summary
1719
+ if not s["calibrated"] and s.get("pointKind") in evidence_kinds
1720
+ ]
1721
+ if uncalibrated:
1722
+ ids = [s["id"] for s in uncalibrated[:10]]
1723
+ msg = (
1724
+ f"{len(uncalibrated)} uncalibrated evidence points. "
1725
+ f"First 10: {ids}. Run calibrate_summary() for full guidance."
1726
+ )
1727
+ raise CalibrationError(msg)
1728
+ if factors is not None:
1729
+ operator_ids = [f if isinstance(f, str) else f[0] for f in factors]
1730
+ elif anchors is not None:
1731
+ # BFS subgraph selection from anchor points
1732
+ operator_ids = self._select_subgraph(anchors, max_hops=max_hops,
1733
+ rel_filter=rel_filter,
1734
+ direction=direction)
1735
+ else:
1736
+ factors_data, _ = proj.extract_svbp_factors()
1737
+ operator_ids = [f[0] for f in factors_data]
1738
+ if not operator_ids:
1739
+ return {"iterations": 0, "converged": True, "confidences": {}}
1740
+ # Lazy consistency (#85): if dirty roots exist and this is a
1741
+ # whole-graph/auto-extract computation, dream the dirty subgraph
1742
+ # first so the auto-extracted factors see stabilized values.
1743
+ if factors is None and anchors is None and self._dirty_roots:
1744
+ self.dream(dirty_only=True)
1745
+ # Re-extract factors after dreaming (graph may have changed).
1746
+ factors_data, _ = proj.extract_svbp_factors()
1747
+ operator_ids = [f[0] for f in factors_data]
1748
+ if not operator_ids:
1749
+ return {"iterations": 0, "converged": True, "confidences": {}}
1750
+ iterations, converged = ep.run(operator_ids, evidence=self._evidence)
1751
+ confidences = {}
1752
+ proj = self._get_proj()
1753
+ from datetime import datetime, timezone
1754
+ now = datetime.now(timezone.utc).isoformat()
1755
+ for claim_id in ep._affected_claims(operator_ids):
1756
+ conf = ep.compute_confidence(claim_id)
1757
+ confidences[claim_id] = conf
1758
+ # Write back mean confidence to node property
1759
+ proj.g.query(
1760
+ "MATCH (n:Point {id:$id}) SET n.confidence = $c, n.updatedAt = $now",
1761
+ params={"id": claim_id, "c": conf["mean"], "now": now},
1762
+ )
1763
+ return {"iterations": iterations, "converged": converged, "confidences": confidences}
1764
+
1765
+ def _hydrate_evidence(self) -> None:
1766
+ """Load graph-persisted baselines (baseline_set=true) into _evidence.
1767
+
1768
+ Idempotent — only adds claim ids not already present. Shared by
1769
+ compute_confidence and the Dreamer (#330) so dream runs honour the
1770
+ same persistent evidence contract as explicit confidence reads.
1771
+ """
1772
+ proj = self._get_proj()
1773
+ rows = proj.g.query(
1774
+ "MATCH (n:Point) WHERE n.baseline_set = true AND n.ep_alpha IS NOT NULL "
1775
+ "RETURN n.id, n.ep_alpha, n.ep_beta"
1776
+ ).result_set
1777
+ for pid, alpha, beta in rows:
1778
+ if pid not in self._evidence:
1779
+ self._evidence[pid] = (alpha, beta)
1780
+
1781
+ def set_point_baseline(self, claim_id: str, alpha: float, beta: float, *,
1782
+ source: str = "explicit") -> dict:
1783
+ """Set Beta prior evidence for a claim. Persists to graph immediately.
1784
+
1785
+ ``source`` records the baseline's provenance (``baseline_source`` graph
1786
+ property): "explicit" (default) — manual/hosted baseline, NEVER
1787
+ recomputed by ``_apply_source_inheritance``; "inherited" — derived from
1788
+ Source evidence, recomputed per EP run subject to the per-point time
1789
+ gate (``n.inherited_at``). Explicit baselines are always distinguishable
1790
+ from legacy ``baseline_set=true`` rows (issue #398 2x2 mapping).
1791
+ """
1792
+ self._evidence[claim_id] = (alpha, beta)
1793
+ # Persist to graph so baselines survive SDK restarts
1794
+ proj = self._get_proj()
1795
+ proj.g.query(
1796
+ "MATCH (n:Point {id: $id}) "
1797
+ "SET n.ep_alpha = $a, n.ep_beta = $b, n.baseline_set = true, "
1798
+ " n.baseline_source = $src",
1799
+ params={"id": claim_id, "a": alpha, "b": beta, "src": source},
1800
+ )
1801
+ # Dreaming (#85, P1): a baseline change alters the prior — neighbors
1802
+ # whose confidence derived from this claim are now stale.
1803
+ self._mark_dirty([claim_id])
1804
+ return {"claim_id": claim_id, "alpha": alpha, "beta": beta, "source": source}
1805
+
1806
+ def _invalidate_inheritance_gate(self, point_ids: list[str]) -> None:
1807
+ """Dirty-mark the per-point recompute gate for inherited baselines.
1808
+
1809
+ Called by write events that change the inputs of source inheritance
1810
+ (point created from a tiered source, extractedFrom edge deleted, source
1811
+ tier/assessment changed). Clears the point's ``inherited_at`` stamp so
1812
+ the next ``_apply_source_inheritance`` recomputes immediately regardless
1813
+ of the time-gate interval.
1814
+ """
1815
+ if not point_ids:
1816
+ return
1817
+ proj = self._get_proj()
1818
+ proj.g.query(
1819
+ "MATCH (n:Point) WHERE n.id IN $ids REMOVE n.inherited_at",
1820
+ params={"ids": point_ids},
1821
+ )
1822
+ self._mark_dirty(point_ids)
1823
+
1824
+ def get_confidence(self, claim_id: str) -> dict:
1825
+ """Get EP confidence for a claim: {mean, variance, alpha, beta}.
1826
+
1827
+ Lazy consistency (#85): if the claim is a dirty root (confidence
1828
+ diverged after writes), dream it first so reads return fresh values.
1829
+ """
1830
+ if claim_id in self._dirty_roots:
1831
+ self.dream(dirty_only=True)
1832
+ return self._get_ep().compute_confidence(claim_id)
1833
+
1834
+ def _apply_source_inheritance(self, recency_decay: float | None = None,
1835
+ recompute_interval: float | None = None):
1836
+ """Apply source credibility (tier → Beta prior) to Points via extractedFrom.
1837
+
1838
+ Issue #398 — log-scale multi-source aggregation (replaces
1839
+ highest-tier-wins) through the real graph path:
1840
+
1841
+ - Tier resolution per source: explicit ``credibilityTier`` >
1842
+ ``sourceKind`` tier-form > registry default (``SOURCE_KIND_DEFAULTS``)
1843
+ > None (neutral — no inheritance, preserving the opt-in guard).
1844
+ - Aggregation: pinned formula
1845
+ ``pc_t = log2(N_t+1) * decay_t * mean_i(base_pc(tier_i) * factor_i)``
1846
+ with ``decay_t`` keyed on the tier's MOST-RECENT source (T0 exempt);
1847
+ per-source ``factor_i`` = assessment factor (1.0 until assess_source
1848
+ lands — Task 5).
1849
+ - Positive-only: NAND contradiction is EP's factor domain — inheritance
1850
+ never folds negative pseudo-counts (double-count guard).
1851
+ - Baseline provenance (2x2 mapping): explicit baselines (baseline_source
1852
+ = 'explicit' or legacy baseline_set=true) are NEVER recomputed;
1853
+ inherited baselines (baseline_source='inherited') recompute per run
1854
+ subject to the per-point time gate (``n.inherited_at``); points with
1855
+ no baseline (baseline_source IS NULL AND baseline_set IS NOT true)
1856
+ are ALWAYS eligible.
1857
+ - Gate: recompute at most once per ``recompute_interval`` (default 3600s,
1858
+ env TORTOISE_EP_REINHERIT_INTERVAL; 0 = always), unless the gate was
1859
+ dirty-marked by a write event. Epsilon guard (rel 1e-9) suppresses
1860
+ identical rewrites; ``inherited_at`` is always refreshed on a
1861
+ dirty-marked recompute so dirty points settle after one pass.
1862
+ - Assessment points (pointKind='assessment') are excluded — they are
1863
+ evidence ABOUT sources, not extracted FROM them.
1864
+
1865
+ ep.py is untouched (additive-only — another issue owns EP propagation).
1866
+ """
1867
+ import os
1868
+ from datetime import datetime, timezone
1869
+ from tortoise.source_credibility import (
1870
+ aggregate_prior,
1871
+ assessment_factor,
1872
+ resolve_tier,
1873
+ )
1874
+
1875
+ if recency_decay is None:
1876
+ recency_decay = float(os.environ.get("TORTOISE_EP_RECENCY_DECAY", "0.95"))
1877
+ if recompute_interval is None:
1878
+ recompute_interval = float(
1879
+ os.environ.get("TORTOISE_EP_REINHERIT_INTERVAL", "3600")
1880
+ )
1881
+ proj = self._get_proj()
1882
+ now = datetime.now(timezone.utc)
1883
+ from collections import defaultdict
1884
+ # Per-source assessment factors (latest per (url, assessor), outdated
1885
+ # filtered, reputation snapshotted at write). Batched — one query.
1886
+ factor_by_source: dict[str, float] = {}
1887
+ arows = proj.g.query(
1888
+ "MATCH (p:Point {pointKind:'assessment'}) "
1889
+ "WHERE (p.outdated IS NULL OR p.outdated = false) "
1890
+ "RETURN p.targetSource, p.assessor, p.score, "
1891
+ "coalesce(p.assessorReputation, 0.5), p.createdAt "
1892
+ "ORDER BY p.createdAt",
1893
+ params={},
1894
+ ).result_set
1895
+ latest_by_source: dict[str, dict[str, tuple[float, float]]] = defaultdict(dict)
1896
+ for tsrc, assessor, score, rep, _created in arows:
1897
+ if not tsrc:
1898
+ continue
1899
+ try:
1900
+ latest_by_source[tsrc][assessor] = (float(rep), float(score))
1901
+ except (TypeError, ValueError):
1902
+ continue
1903
+ for tsrc, by_assessor in latest_by_source.items():
1904
+ factor_by_source[tsrc] = assessment_factor(by_assessor.values())
1905
+
1906
+ # Inherit-eligible points:
1907
+ # (baseline_source IS NULL AND baseline_set IS NOT true) → always eligible
1908
+ # (baseline_source = 'inherited') → gated by inherited_at
1909
+ where = (
1910
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
1911
+ "AND (n.pointKind IS NULL OR n.pointKind <> 'assessment') "
1912
+ "AND ("
1913
+ " (n.baseline_source IS NULL AND (n.baseline_set IS NULL OR n.baseline_set = false)) "
1914
+ " OR n.baseline_source = 'inherited'"
1915
+ ") "
1916
+ "AND (s.credibilityTier IS NOT NULL OR s.sourceKind IS NOT NULL) "
1917
+ )
1918
+ rows = proj.g.query(
1919
+ f"MATCH (n:Point)-[:extractedFrom]->(s:Source) {where} "
1920
+ "RETURN n.id, s.url, s.credibilityTier, s.sourceKind, "
1921
+ "s.sourceDate, s.ingestedAt, n.baseline_source, n.inherited_at",
1922
+ params={},
1923
+ ).result_set
1924
+
1925
+ # Collect per-point source evidence
1926
+ from collections import defaultdict
1927
+ point_sources: dict[str, list[dict]] = defaultdict(list)
1928
+ for pid, url, ctier, skind, sdate, ingested, bl_src, inherited_at in rows:
1929
+ tier = resolve_tier(ctier, skind)
1930
+ if tier is None:
1931
+ continue # neutral source — no inheritance contribution
1932
+ point_sources[pid].append({
1933
+ "url": url, "tier": tier, "sourceDate": sdate,
1934
+ "ingestedAt": ingested,
1935
+ })
1936
+
1937
+ # Revert: points with an inherited baseline but NO eligible sources
1938
+ # (all edges deleted or all sources neutral) return to neutral — subject
1939
+ # to the same per-point gate (dirty-marked or interval elapsed).
1940
+ if point_sources:
1941
+ sourced_ids = set(point_sources)
1942
+ else:
1943
+ sourced_ids = set()
1944
+ revert_rows = proj.g.query(
1945
+ "MATCH (n:Point) WHERE n.baseline_source = 'inherited' "
1946
+ "AND (n.pointKind IS NULL OR n.pointKind <> 'assessment') "
1947
+ "RETURN n.id, n.inherited_at",
1948
+ params={},
1949
+ ).result_set
1950
+ for pid, inherited_at in revert_rows:
1951
+ if pid in sourced_ids:
1952
+ continue
1953
+ # Gate check (same as write path)
1954
+ if inherited_at is not None and recompute_interval > 0:
1955
+ try:
1956
+ last = datetime.fromisoformat(str(inherited_at).replace("Z", "+00:00"))
1957
+ if last.tzinfo is None:
1958
+ last = last.replace(tzinfo=timezone.utc)
1959
+ age = (now - last).total_seconds()
1960
+ except (ValueError, TypeError):
1961
+ age = recompute_interval + 1
1962
+ if age < recompute_interval:
1963
+ continue # within interval and not dirty-marked → keep
1964
+ proj.g.query(
1965
+ "MATCH (n:Point {id:$id}) REMOVE n.ep_alpha, n.ep_beta, "
1966
+ "n.baseline_set, n.baseline_source, n.inherited_at",
1967
+ params={"id": pid},
1968
+ )
1969
+ self._mark_dirty([pid])
1970
+
1971
+ for pid, sources in point_sources.items():
1972
+ # Fetch the point's current baseline marker state
1973
+ row = proj.g.query(
1974
+ "MATCH (n:Point {id:$id}) RETURN n.baseline_source, n.inherited_at, "
1975
+ "coalesce(n.ep_alpha, 1.0), coalesce(n.ep_beta, 1.0)",
1976
+ params={"id": pid},
1977
+ ).result_set
1978
+ bl_src, inherited_at, cur_a, cur_b = row[0] if row else (None, None, 1.0, 1.0)
1979
+
1980
+ is_inherited = bl_src == "inherited"
1981
+ if is_inherited and inherited_at is not None and recompute_interval > 0:
1982
+ try:
1983
+ last = datetime.fromisoformat(str(inherited_at).replace("Z", "+00:00"))
1984
+ if last.tzinfo is None:
1985
+ last = last.replace(tzinfo=timezone.utc)
1986
+ age = (now - last).total_seconds()
1987
+ except (ValueError, TypeError):
1988
+ age = recompute_interval + 1 # stale stamp → recompute
1989
+ if age < recompute_interval:
1990
+ continue # within interval and not dirty-marked → skip
1991
+
1992
+ # Per-source assessment factor (clamped [0.1, 2.0]); factor = 1.0
1993
+ # when no assessments — exact tier priors preserved.
1994
+ groups = [
1995
+ (src["tier"], src["sourceDate"], src["ingestedAt"],
1996
+ factor_by_source.get(src["url"], 1.0))
1997
+ for src in sources
1998
+ ]
1999
+ alpha, beta = aggregate_prior(
2000
+ groups, recency_decay=recency_decay, now=now,
2001
+ )
2002
+
2003
+ # Epsilon guard: skip identical rewrites (no dirty churn).
2004
+ if is_inherited and abs(alpha - cur_a) < 1e-9 * max(1.0, abs(alpha)) \
2005
+ and abs(beta - cur_b) < 1e-9 * max(1.0, abs(beta)):
2006
+ # Refresh the gate stamp so dirty points settle after one pass.
2007
+ self._touch_inherited_at(pid, now)
2008
+ continue
2009
+
2010
+ self.set_point_baseline(pid, alpha, beta, source="inherited")
2011
+ self._touch_inherited_at(pid, now)
2012
+
2013
+ def _touch_inherited_at(self, point_id: str, now) -> None:
2014
+ """Stamp the per-point inheritance gate timestamp (graph-persisted)."""
2015
+ proj = self._get_proj()
2016
+ proj.g.query(
2017
+ "MATCH (n:Point {id:$id}) SET n.inherited_at = $ts",
2018
+ params={"id": point_id, "ts": now.isoformat()},
2019
+ )
2020
+
2021
+ def calibrate_summary(self) -> list[dict]:
2022
+ """Audit graph calibration state. Returns per-point guidance.
2023
+
2024
+ Checks baseline_set flag on non-operator Points. For uncalibrated
2025
+ points, traverses extractedFrom→Source to check for inherited credibilityTier.
2026
+ """
2027
+ proj = self._get_proj()
2028
+ where = "WHERE (n.is_operator IS NULL OR n.is_operator = false)"
2029
+ params = {}
2030
+
2031
+ from tortoise.source_credibility import resolve_tier
2032
+ rows = proj.g.query(
2033
+ f"MATCH (n:Point) {where} "
2034
+ "AND (n.pointKind IS NULL OR n.pointKind <> 'assessment') "
2035
+ "OPTIONAL MATCH (n)-[:extractedFrom]->(s:Source) "
2036
+ "RETURN n.id, n.content, n.pointKind, "
2037
+ "coalesce(n.baseline_set, false) AS calibrated, "
2038
+ "s.credibilityTier, s.sourceKind, s.url AS src_url",
2039
+ params=params,
2040
+ ).result_set
2041
+
2042
+ results = []
2043
+ for row in rows:
2044
+ pid, content, pk, calibrated, ctier, skind, src_url = row
2045
+ item = {"id": pid, "content": content, "pointKind": pk, "calibrated": calibrated}
2046
+ # Effective tier: explicit credibilityTier > sourceKind tier-form >
2047
+ # registry default (issue #398 Task 6 — legacy-inherited advisory).
2048
+ eff_tier = resolve_tier(ctier, skind)
2049
+
2050
+ if not calibrated:
2051
+ if src_url and eff_tier:
2052
+ item["suggestion"] = (
2053
+ f"Inherited {eff_tier} from Source {src_url} — run "
2054
+ f"compute_confidence() to apply"
2055
+ )
2056
+ elif src_url and not eff_tier:
2057
+ item["suggestion"] = (
2058
+ f"Source {src_url} is untiered — call "
2059
+ f"set_source_tier('{src_url}', 'T0'..'T4') or "
2060
+ f"create_source(url, kind, tier=...) "
2061
+ f"(covers all points from this source)"
2062
+ )
2063
+ else:
2064
+ item["suggestion"] = (
2065
+ f"Call set_point_baseline('{pid}', alpha, beta) "
2066
+ f"or recreate with credibility kwarg"
2067
+ )
2068
+ else:
2069
+ # Legacy-inherited advisory: explicit/inherited baseline whose
2070
+ # source was re-tiered — suggest re-derivation via the writer.
2071
+ if src_url and ctier and item.get("calibrated"):
2072
+ item["note"] = (
2073
+ f"Source {src_url} tier {ctier} — baseline may predate "
2074
+ f"issue #398; re-derive via set_source_tier"
2075
+ )
2076
+ results.append(item)
2077
+
2078
+ # Deduplicate: keep one entry per Point ID, prefer Source-based suggestions
2079
+ seen = {}
2080
+ deduped = []
2081
+ for item in results:
2082
+ pid = item["id"]
2083
+ if pid not in seen:
2084
+ seen[pid] = item
2085
+ deduped.append(item)
2086
+ elif "Source" in str(item.get("suggestion", "")) and "Source" not in str(seen[pid].get("suggestion", "")):
2087
+ for i, d in enumerate(deduped):
2088
+ if d["id"] == pid:
2089
+ deduped[i] = item
2090
+ break
2091
+ seen[pid] = item
2092
+ return deduped
2093
+
2094
+
2095
+ # ── P0 Group 3: Checkpoint, Diary, Status, Analyze, Ingest ────
2096
+
2097
+ def _content_exists(self, content: str) -> str | None:
2098
+ """Return point ID if a point with this content hash exists, else None."""
2099
+ ch = _content_hash(content)
2100
+ proj = self._get_proj()
2101
+ rows = proj.g.query(
2102
+ "MATCH (n:Point {content_hash:$ch}) "
2103
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2104
+ "RETURN n.id",
2105
+ params={"ch": ch},
2106
+ ).result_set
2107
+ return rows[0][0] if rows else None
2108
+
2109
+ def checkpoint(self, items: list[dict], agent_name: str = "checkpoint",
2110
+ threshold: float = 0.95) -> dict:
2111
+ """Session batch save — two-tier dedup (content hash + embedding similarity).
2112
+
2113
+ Each item: {wing, room, content}. Returns {filed: N, duplicates: M}.
2114
+ threshold: cosine similarity for semantic dedup (0.0-1.0).
2115
+ Set to 1.0 to disable semantic dedup (hash-only).
2116
+ """
2117
+ from datetime import datetime, timezone
2118
+ filed, duplicates = 0, 0
2119
+ proj = self._get_proj()
2120
+ now = datetime.now(timezone.utc).isoformat()
2121
+
2122
+ # Tier 1: content hash dedup
2123
+ to_check: list[tuple[dict, str]] = []
2124
+ seen: set[str] = set()
2125
+ for item in items:
2126
+ content = item["content"]
2127
+ ch = _content_hash(content)
2128
+ if ch in seen or self._content_exists(content):
2129
+ duplicates += 1
2130
+ continue
2131
+ seen.add(ch)
2132
+ to_check.append((item, ch))
2133
+
2134
+ if not to_check:
2135
+ return {"filed": 0, "duplicates": duplicates}
2136
+
2137
+ # Tier 2: embedding similarity dedup (GAP-08)
2138
+ to_file = to_check
2139
+ if threshold < 1.0:
2140
+ try:
2141
+ to_file = self._semantic_dedup(to_check, threshold)
2142
+ except ImportError:
2143
+ # Expected in zero-dependency environments — hash-only fallback.
2144
+ # #330: previously a bare `except Exception: pass` swallowed
2145
+ # real failures silently; log the designed fallback at INFO.
2146
+ _logger.info(
2147
+ "Semantic dedup unavailable (embeddings deps missing) — "
2148
+ "hash-only fallback"
2149
+ )
2150
+ to_file = to_check
2151
+ except Exception as e:
2152
+ # #330: real dedup backend failures must be observable — a
2153
+ # silent degrade to hash-only dedup would file duplicates.
2154
+ _logger.warning(
2155
+ "Semantic dedup failed — falling back to hash-only dedup: %s", e
2156
+ )
2157
+ to_file = to_check
2158
+
2159
+ duplicates += len(to_check) - len(to_file)
2160
+
2161
+ for item, ch in to_file:
2162
+ p = self.create_point(
2163
+ "checkpoint-item", item["content"],
2164
+ wing=item.get("wing", ""),
2165
+ room=item.get("room", ""),
2166
+ content_hash=ch,
2167
+ )
2168
+ # GAP-07: emit EventRecorded for provenance
2169
+ try:
2170
+ proj.apply({
2171
+ "type": "EventRecorded",
2172
+ "id": ulid(),
2173
+ "eventKind": "pointAdded",
2174
+ "subject": agent_name,
2175
+ "object": p["id"],
2176
+ "startedAt": now,
2177
+ })
2178
+ except Exception:
2179
+ _logger.warning("Failed to emit provenance event for point %s", p["id"])
2180
+ filed += 1
2181
+
2182
+ monitoring.record_ingest()
2183
+ return {"filed": filed, "duplicates": duplicates}
2184
+
2185
+ def _semantic_dedup(self, candidates: list[tuple[dict, str]],
2186
+ threshold: float) -> list[tuple[dict, str]]:
2187
+ """Filter candidates by embedding similarity against existing checkpoint items."""
2188
+ import numpy as np
2189
+ proj = self._get_proj()
2190
+ rows = proj.g.query(
2191
+ "MATCH (n:Point {pointKind:'checkpoint-item'}) "
2192
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2193
+ "RETURN n.content"
2194
+ ).result_set
2195
+ existing = [r[0] for r in rows if r[0]]
2196
+ if not existing:
2197
+ return candidates
2198
+
2199
+ new_texts = [item["content"] for item, _ch in candidates]
2200
+ # ponytail: prefer sentence_transformers; TF-IDF fallback for zero-dependency path
2201
+ try:
2202
+ from sentence_transformers import SentenceTransformer
2203
+ model = SentenceTransformer("all-MiniLM-L6-v2")
2204
+ vecs = model.encode(existing + new_texts, show_progress_bar=False)
2205
+ except ImportError:
2206
+ from sklearn.feature_extraction.text import TfidfVectorizer
2207
+ vecs = TfidfVectorizer().fit_transform(existing + new_texts).toarray()
2208
+
2209
+ e_vecs, n_vecs = vecs[:len(existing)], vecs[len(existing):]
2210
+
2211
+ def _norm(v):
2212
+ n = np.linalg.norm(v, axis=1, keepdims=True)
2213
+ n[n == 0] = 1
2214
+ return v / n
2215
+
2216
+ max_sims = (_norm(n_vecs) @ _norm(e_vecs).T).max(axis=1)
2217
+ return [(item, ch) for i, (item, ch) in enumerate(candidates)
2218
+ if max_sims[i] < threshold]
2219
+
2220
+ def diary_write(self, agent_name: str, entry: str,
2221
+ topic: str | None = None, wing: str | None = None) -> dict:
2222
+ """Write an agent diary entry. Returns the created Point."""
2223
+ from datetime import datetime, timezone
2224
+ props: dict[str, Any] = {"authoredBy": agent_name}
2225
+ if topic:
2226
+ props["topic"] = topic
2227
+ # P1 #49: use wing property only — context is deprecated
2228
+ if wing:
2229
+ props["wing"] = wing
2230
+ return self.create_point("diary", entry, **props)
2231
+
2232
+ def diary_read(self, agent_name: str, last_n: int = 10,
2233
+ wing: str | None = None) -> list[dict]:
2234
+ """Read recent diary entries for an agent, newest first."""
2235
+ proj = self._get_proj()
2236
+ if wing:
2237
+ rows = proj.g.query(
2238
+ "MATCH (n:Point {pointKind:'diary', authoredBy:$agent, wing:$wing}) "
2239
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2240
+ "RETURN properties(n) ORDER BY n.createdAt DESC LIMIT $lim",
2241
+ params={"agent": agent_name, "wing": wing, "lim": last_n},
2242
+ ).result_set
2243
+ else:
2244
+ rows = proj.g.query(
2245
+ "MATCH (n:Point {pointKind:'diary', authoredBy:$agent}) "
2246
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2247
+ "RETURN properties(n) ORDER BY n.createdAt DESC LIMIT $lim",
2248
+ params={"agent": agent_name, "lim": last_n},
2249
+ ).result_set
2250
+ return [r[0] for r in rows]
2251
+
2252
+ def status(self) -> dict:
2253
+ """Graph health + entity counts + FalkorDB connectivity.
2254
+
2255
+ Returns {connected, counts: {Point, Event, ...}, total_entities}.
2256
+ """
2257
+ proj = self._get_proj()
2258
+ connected = False
2259
+ try:
2260
+ proj.g.query("MATCH (n) RETURN count(n) LIMIT 1")
2261
+ connected = True
2262
+ except Exception:
2263
+ pass
2264
+ counts = self.taxonomy()
2265
+ total = sum(counts.values())
2266
+ result = {"connected": connected, "counts": counts, "total_entities": total}
2267
+ if self._namespace:
2268
+ result["namespace"] = self._namespace
2269
+ return result
2270
+
2271
+ def ingest_corpus(self, directory: str, eventKind: str = "DocumentCreated",
2272
+ extract_metadata: bool = False, llm_model: str | None = "gpt-5-mini",
2273
+ progress_file: str | None = None) -> dict:
2274
+ """Batch ingestion — walk directory, parse YAML frontmatter,
2275
+ create/update Event nodes. Returns {ingested, updated, skipped, failed, errors}.
2276
+
2277
+ When eventKind='AgentSession' and extract_metadata=True, runs LLM/fallback
2278
+ metadata extraction on session content before creating the Event.
2279
+ """
2280
+ import re
2281
+ import os as _os
2282
+ import json as _json
2283
+ from pathlib import Path
2284
+ from datetime import datetime, timezone
2285
+
2286
+ # #329: ingest path validation — absolute, no `..`, and under the
2287
+ # optional TORTOISE_INGEST_BASE_DIR base. The stdio/CLI surface is
2288
+ # operator-trusted, but the directory walk reads host files: bound it.
2289
+ from .security import ingest_dir_is_safe, resolve_under_base
2290
+ ingest_base = None
2291
+ raw_base = _os.environ.get("TORTOISE_INGEST_BASE_DIR")
2292
+ if raw_base:
2293
+ ingest_base = _os.path.realpath(_os.path.expanduser(raw_base))
2294
+ if not ingest_dir_is_safe(directory, ingest_base):
2295
+ raise ValueError(
2296
+ f"Unsafe ingest directory: {directory!r}. Directory must be "
2297
+ f"absolute, contain no '..' components, and resolve under "
2298
+ f"TORTOISE_INGEST_BASE_DIR when set ({ingest_base or '<unset>'})."
2299
+ )
2300
+ if progress_file is not None:
2301
+ if not isinstance(progress_file, str) or not progress_file:
2302
+ raise ValueError("progress_file must be a non-empty string.")
2303
+ if not _os.path.isabs(progress_file):
2304
+ raise ValueError(f"progress_file must be absolute: {progress_file!r}")
2305
+ if ".." in Path(progress_file).parts:
2306
+ raise ValueError(f"progress_file contains '..': {progress_file!r}")
2307
+ if ingest_base is not None and resolve_under_base(progress_file, ingest_base) is None:
2308
+ raise ValueError(
2309
+ f"progress_file {progress_file!r} not under TORTOISE_INGEST_BASE_DIR."
2310
+ )
2311
+
2312
+ _FM_RE = re.compile(r'^---\s*\n(.*?)\n---', re.DOTALL)
2313
+ ingested, updated, skipped, failed = 0, 0, 0, 0
2314
+ errors: list[dict] = []
2315
+ now = datetime.now(timezone.utc).isoformat()
2316
+ proj = self._get_proj()
2317
+
2318
+ files = sorted(Path(directory).rglob("*.md"))
2319
+
2320
+ # Resume from progress file
2321
+ completed_files: list[str] = []
2322
+ if progress_file:
2323
+ try:
2324
+ with open(progress_file) as pf:
2325
+ progress = _json.load(pf)
2326
+ completed_files = progress.get("completed_files", [])
2327
+ except Exception:
2328
+ pass
2329
+ processed_set = set(completed_files)
2330
+
2331
+ for i, filepath in enumerate(files):
2332
+ rel_path = str(filepath)
2333
+ if rel_path in processed_set:
2334
+ skipped += 1
2335
+ continue
2336
+
2337
+ try:
2338
+ text = filepath.read_text(encoding="utf-8")
2339
+ except Exception as e:
2340
+ failed += 1
2341
+ errors.append({"file": rel_path, "error": str(e), "retryable": False})
2342
+ continue
2343
+
2344
+ m = _FM_RE.match(text)
2345
+ frontmatter: dict = {}
2346
+ if m:
2347
+ try:
2348
+ import yaml as _yaml
2349
+ parsed = _yaml.safe_load(m.group(1))
2350
+ if isinstance(parsed, dict):
2351
+ frontmatter = parsed
2352
+ # YAML types (bool/int) must not leak into string fields
2353
+ # (regression vs old line-by-line parser). Coerce known
2354
+ # string fields to str.
2355
+ for _k in ("doc_status", "format", "version", "title",
2356
+ "sessionId", "session_id", "agent"):
2357
+ if _k in frontmatter and frontmatter[_k] is not None:
2358
+ frontmatter[_k] = str(frontmatter[_k])
2359
+ except Exception:
2360
+ pass # fallback to empty dict
2361
+
2362
+ # #330: content identity hash shared by both modes (hashlib is
2363
+ # module-imported). byte-identical re-ingest -> skipped.
2364
+ file_hash = hashlib.sha256(text.encode()).hexdigest()
2365
+
2366
+ if eventKind == "AgentSession":
2367
+ # AgentSession branch — session indexing with metadata extraction
2368
+ session_id = frontmatter.get("sessionId") or frontmatter.get("session_id") or f"file_{filepath.stem}"
2369
+ event_id = f"session_{session_id}"
2370
+ name = frontmatter.get("title", filepath.stem)
2371
+
2372
+ # Check dedup
2373
+ exists_rows = proj.g.query(
2374
+ "MATCH (e:Event {eventId:$eid}) RETURN properties(e)",
2375
+ params={"eid": event_id},
2376
+ ).result_set
2377
+
2378
+ if exists_rows:
2379
+ existing_props = exists_rows[0][0]
2380
+ # #330: skip unchanged + complete events. has_keywords is the
2381
+ # sole completeness signal (an eventStatus disjunct would skip
2382
+ # incomplete sessions that still need enrichment).
2383
+ has_keywords = bool(existing_props.get("keywords"))
2384
+ if existing_props.get("file_hash") == file_hash and has_keywords:
2385
+ skipped += 1
2386
+ completed_files.append(rel_path)
2387
+ continue
2388
+ # Always extract keywords (even without LLM)
2389
+ from .session_indexer import extract_keywords_from_frontmatter as _kw_fallback
2390
+ if extract_metadata:
2391
+ from .session_indexer import extract_metadata as _extract
2392
+ try:
2393
+ metadata = _extract(text, llm_model)
2394
+ except Exception:
2395
+ metadata = _kw_fallback(text)
2396
+ else:
2397
+ metadata = _kw_fallback(text)
2398
+
2399
+ merged_keywords = list(dict.fromkeys(
2400
+ existing_props.get("keywords", []) + metadata.get("keywords", [])
2401
+ ))[:20]
2402
+ existing_arc = existing_props.get("content_metadata", "{}")
2403
+ try:
2404
+ existing_arc = _json.loads(existing_arc) if isinstance(existing_arc, str) else existing_arc
2405
+ except Exception:
2406
+ existing_arc = {}
2407
+ # #330: dedup + cap the narrative arc so repeated enrichment
2408
+ # of unchanged files never grows it unboundedly (and the
2409
+ # state-change comparison below stays deterministic). Arc
2410
+ # entries may be dicts (phase/topic/decisions), so dedup via
2411
+ # a canonical JSON key (str-sorted to tolerate mixed-type
2412
+ # keys), not dict.fromkeys.
2413
+ _arc_seen = {}
2414
+ for _phase in (existing_arc.get("narrative_arc", [])
2415
+ + metadata.get("narrative_arc", [])):
2416
+ _key = _json.dumps(_phase, sort_keys=True, default=str)
2417
+ _arc_seen.setdefault(_key, _phase)
2418
+ _merged_phases = list(_arc_seen.values())
2419
+ # Cap while preferring genuinely-new phases: keep existing
2420
+ # ones first (already-merged), then append new ones up to
2421
+ # the cap so a full arc never starves fresh phases.
2422
+ _existing_phases = existing_arc.get("narrative_arc", [])
2423
+ _new_only = [p for p in _merged_phases
2424
+ if _json.dumps(p, sort_keys=True, default=str)
2425
+ not in {_json.dumps(e, sort_keys=True, default=str)
2426
+ for e in _existing_phases}]
2427
+ new_phases = (_merged_phases[:len(_existing_phases)]
2428
+ + _new_only)[:50]
2429
+
2430
+ # Normalize topics to a comparable, hashable form (#330):
2431
+ # LLM output is unvalidated — a list-of-dicts would crash
2432
+ # set() and abort the whole run.
2433
+ def _norm_topics(t) -> list:
2434
+ t = t or []
2435
+ if not isinstance(t, list):
2436
+ t = [t]
2437
+ return [str(x) for x in t]
2438
+ _new_topics = _norm_topics(metadata.get("topics",
2439
+ existing_props.get("topics", [])))
2440
+ _stored_topics = _norm_topics(existing_props.get("topics"))
2441
+ _stored_keywords = _norm_topics(existing_props.get("keywords"))
2442
+ _new_name = metadata.get("summary", existing_props.get("name", name))
2443
+
2444
+ update_props = {
2445
+ "name": _new_name,
2446
+ "keywords": merged_keywords,
2447
+ "topics": _new_topics,
2448
+ "file_hash": file_hash,
2449
+ "content_metadata": _json.dumps({
2450
+ "schema_version": 1,
2451
+ "summary": metadata.get("summary", ""),
2452
+ "narrative_arc": new_phases,
2453
+ "issues": metadata.get("issues", []),
2454
+ "prs": metadata.get("prs", []),
2455
+ "critical_decisions": metadata.get("critical_decisions", []),
2456
+ }),
2457
+ "message_count": frontmatter.get("message_count", 0),
2458
+ }
2459
+ # #330: unchanged content whose enrichment produced nothing
2460
+ # new counts as skipped, not updated (counter honesty).
2461
+ # Compare the FULL payload that would be written (keywords,
2462
+ # normalized topics, name, narrative_arc, issues/prs/
2463
+ # critical_decisions — the latter feed _connect_issue_objects)
2464
+ # so a real change in any persisted field is never
2465
+ # miscounted as a skip.
2466
+ if existing_props.get("file_hash") == file_hash:
2467
+ _old_meta = existing_arc
2468
+ changed = (
2469
+ set(_norm_topics(merged_keywords)) != set(_stored_keywords)
2470
+ or set(_new_topics) != set(_stored_topics)
2471
+ or _new_name != existing_props.get("name", name)
2472
+ or new_phases != list(existing_arc.get("narrative_arc", []))
2473
+ or _norm_topics(metadata.get("issues", [])) != _norm_topics(_old_meta.get("issues", []))
2474
+ or _norm_topics(metadata.get("prs", [])) != _norm_topics(_old_meta.get("prs", []))
2475
+ or _norm_topics(metadata.get("critical_decisions", [])) != _norm_topics(_old_meta.get("critical_decisions", []))
2476
+ )
2477
+ if not changed:
2478
+ skipped += 1
2479
+ completed_files.append(rel_path)
2480
+ continue
2481
+
2482
+ # #244: (re)compute the session embedding from the merged
2483
+ # surface and store as vecf32 — None when model unavailable.
2484
+ embedding = self._session_embedding(
2485
+ update_props["name"], metadata.get("summary", ""),
2486
+ merged_keywords, update_props["topics"],
2487
+ )
2488
+ proj.g.query(
2489
+ "MATCH (e:Event {eventId:$eid}) SET e += $props, "
2490
+ "e.embedding = CASE WHEN $embedding IS NOT NULL THEN vecf32($embedding) ELSE e.embedding END",
2491
+ params={"eid": event_id, "props": update_props, "embedding": embedding},
2492
+ )
2493
+ updated += 1
2494
+ completed_files.append(rel_path)
2495
+ # Connect issue/PR references to Objects
2496
+ self._connect_issue_objects(event_id, metadata)
2497
+ else:
2498
+ # New session Event — always extract keywords
2499
+ from .session_indexer import extract_keywords_from_frontmatter as _kw_fallback
2500
+ if extract_metadata:
2501
+ from .session_indexer import extract_metadata as _extract
2502
+ try:
2503
+ metadata = _extract(text, llm_model)
2504
+ except Exception:
2505
+ metadata = _kw_fallback(text)
2506
+ else:
2507
+ metadata = _kw_fallback(text)
2508
+
2509
+ props = {
2510
+ "name": metadata.get("summary", name),
2511
+ "eventKind": eventKind,
2512
+ "session_id": session_id,
2513
+ "agent": frontmatter.get("agent", "pi"),
2514
+ "source_file": rel_path,
2515
+ "file_hash": file_hash,
2516
+ "keywords": metadata.get("keywords", []),
2517
+ "topics": metadata.get("topics", []),
2518
+ "message_count": frontmatter.get("message_count", 0),
2519
+ "startedAt": now,
2520
+ "content_metadata": _json.dumps({
2521
+ "schema_version": 1,
2522
+ "summary": metadata.get("summary", ""),
2523
+ "narrative_arc": metadata.get("narrative_arc", []),
2524
+ "issues": metadata.get("issues", []),
2525
+ "prs": metadata.get("prs", []),
2526
+ "critical_decisions": metadata.get("critical_decisions", []),
2527
+ }),
2528
+ "eventStatus": "completed",
2529
+ "classificationLevel": "internal",
2530
+ "format": "markdown",
2531
+ }
2532
+ # #244: compute the session embedding (name + summary +
2533
+ # keywords + topics) and store as vecf32 — None when the
2534
+ # model is unavailable (indexing never depends on it).
2535
+ embedding = self._session_embedding(
2536
+ props["name"], metadata.get("summary", ""),
2537
+ props["keywords"], props["topics"],
2538
+ )
2539
+ proj.g.query(
2540
+ "MERGE (e:Event {eventId:$eid}) SET e += $props, "
2541
+ "e.embedding = CASE WHEN $embedding IS NOT NULL THEN vecf32($embedding) ELSE e.embedding END",
2542
+ params={"eid": event_id, "props": props, "embedding": embedding},
2543
+ )
2544
+ ingested += 1
2545
+ completed_files.append(rel_path)
2546
+ # Connect issue/PR references to Objects
2547
+ self._connect_issue_objects(event_id, metadata)
2548
+ else:
2549
+ # Original DocumentCreated logic
2550
+ doc_id = str(filepath.relative_to(directory))
2551
+ title = frontmatter.get("title", filepath.stem)
2552
+ doc_kind = frontmatter.get("type", frontmatter.get("document_kind", ""))
2553
+ domain = frontmatter.get("domain", frontmatter.get("documentKnowledgeDomain", ""))
2554
+
2555
+ # #330: three-way on ROW PRESENCE (new doc -> zero rows;
2556
+ # legacy event -> row with file_hash=None). RETURN e.file_hash
2557
+ # so byte-identical re-ingest is counted as skipped.
2558
+ exists_rows = proj.g.query(
2559
+ "MATCH (e:Event {eventId:$eid}) RETURN e.file_hash",
2560
+ params={"eid": doc_id},
2561
+ ).result_set
2562
+
2563
+ props = {
2564
+ "title": title,
2565
+ "document_kind": doc_kind,
2566
+ "document_knowledge_domain": domain,
2567
+ "authored_by": frontmatter.get("authoredBy", ""),
2568
+ "owned_by": frontmatter.get("ownedBy", ""),
2569
+ "managed_by": frontmatter.get("managedBy", ""),
2570
+ "governing_agreement": frontmatter.get("governedBy", frontmatter.get("governingAgreement", "")),
2571
+ "doc_status": frontmatter.get("doc_status", "draft"),
2572
+ "format": "markdown",
2573
+ "version": frontmatter.get("version", ""),
2574
+ "createdAt": frontmatter.get("created", now),
2575
+ "updatedAt": frontmatter.get("updated", now),
2576
+ "eventKind": "DocumentCreated",
2577
+ "classificationLevel": "internal",
2578
+ "file_hash": file_hash,
2579
+ }
2580
+
2581
+ if not exists_rows:
2582
+ # New document
2583
+ proj.g.query(
2584
+ "CREATE (e:Event {eventId:$eid}) SET e += $props",
2585
+ params={"eid": doc_id, "props": props},
2586
+ )
2587
+ ingested += 1
2588
+ elif exists_rows[0][0] == file_hash:
2589
+ # Byte-identical re-ingest — nothing to do (#330)
2590
+ skipped += 1
2591
+ else:
2592
+ # Changed content, or legacy event without a stored hash
2593
+ # (None) — update and backfill the hash.
2594
+ proj.g.query(
2595
+ "MATCH (e:Event {eventId:$eid}) SET e += $props",
2596
+ params={"eid": doc_id, "props": props},
2597
+ )
2598
+ updated += 1
2599
+
2600
+ # Progress checkpoint every 100 files
2601
+ if progress_file and (i + 1) % 100 == 0:
2602
+ _save_progress(progress_file, str(directory), len(files),
2603
+ ingested + updated + skipped + failed,
2604
+ ingested, updated, skipped, failed, errors,
2605
+ completed_files=completed_files)
2606
+
2607
+ monitoring.record_ingest()
2608
+
2609
+ if progress_file:
2610
+ _save_progress(progress_file, str(directory), len(files),
2611
+ ingested + updated + skipped + failed,
2612
+ ingested, updated, skipped, failed, errors,
2613
+ completed_files=completed_files)
2614
+
2615
+ return {"ingested": ingested, "updated": updated, "skipped": skipped,
2616
+ "failed": failed, "errors": errors}
2617
+
2618
+ # ── Entity Resolution (GAP-01 #6987) ──────────────────────
2619
+
2620
+ def suggest_entry_points(self, query: str, *, limit: int = 5,
2621
+ kind_filter: str | None = None,
2622
+ graph_ranker=None) -> list[dict]:
2623
+ """Entity resolution — NL query → matching entities from the graph.
2624
+
2625
+ String match on content (Cypher CONTAINS) + embedding fallback.
2626
+ Returns [{id, name, kind, confidence}] sorted by confidence DESC.
2627
+ kind_filter filters by n.pointKind.
2628
+ graph_ranker: optional GraphRanker (tortoise.ranking) to rerank the
2629
+ results with graph signals (persisted EP confidence, connectivity,
2630
+ recency) — #25. Off by default for backward compatibility.
2631
+ """
2632
+ if limit < 1:
2633
+ raise ValueError(f"limit must be >= 1, got {limit}")
2634
+ q = query.strip()[:500] # ponytail: bound to 500 chars; embedding APIs have token limits
2635
+ if not q:
2636
+ return []
2637
+
2638
+ proj = self._get_proj()
2639
+ clauses = ["(n.is_operator IS NULL OR n.is_operator = false)",
2640
+ "toLower(n.content) CONTAINS toLower($q)"]
2641
+ params = {"q": q}
2642
+ if kind_filter:
2643
+ clauses.append("n.pointKind = $kf")
2644
+ params["kf"] = kind_filter
2645
+
2646
+ where = " AND ".join(clauses)
2647
+ rows = proj.g.query(
2648
+ f"MATCH (n:Point) WHERE {where} "
2649
+ "RETURN n.id, n.content, n.pointKind",
2650
+ params=params,
2651
+ ).result_set
2652
+
2653
+ results = []
2654
+ q_lower = q.lower()
2655
+ for pid, content, kind in rows:
2656
+ # ponytail: guard empty content (stub nodes may have '')
2657
+ if not content:
2658
+ continue
2659
+ # Confidence formula (#22): exact match → 1.0, partial match →
2660
+ # [0.5, 1.0) via length ratio, smoothed to avoid scale collapse.
2661
+ # len(q)/len(content) alone would give 0.001 for 1-char in 1000-char
2662
+ # doc and 0.5 for 5-char in 10-char — not comparable. The 0.5 offset
2663
+ # ensures all substring matches score ≥ 0.5, reserving [0, 0.5) for
2664
+ # the hybrid fallback path (which has no substring match at all).
2665
+ # The fallback band-normalizes its RRF scores into [0, 0.5) (#22).
2666
+ if content.lower() == q_lower:
2667
+ confidence = 1.0
2668
+ else:
2669
+ ratio = len(q) / len(content)
2670
+ confidence = round(0.5 + 0.5 * ratio, 4)
2671
+ results.append({"id": pid, "name": content, "kind": kind or "", "confidence": confidence})
2672
+
2673
+ results.sort(key=lambda r: r["confidence"], reverse=True)
2674
+ results = results[:limit]
2675
+
2676
+ # Hybrid fallback if no string matches (Phase 0, #7748).
2677
+ # Confidence contract (#22): fallback results must live in the [0, 0.5)
2678
+ # band reserved by the substring-match formula above. Raw RRF scores are
2679
+ # NOT comparable to that band — rank-based fusion caps near 0.016 per
2680
+ # ranked list (~0.05 with 3 fused lists) while embedded FTS raw scores
2681
+ # are unbounded above — so `rrf * 0.5` landed anywhere from ~0.008 to
2682
+ # >1.0, tripping downstream conf > 0.3 thresholds. Band-normalize:
2683
+ # scale each RRF score by the set's max so the strongest fallback hit
2684
+ # lands at 0.49 (just under the 0.5 boundary) and weaker hits scale
2685
+ # proportionally. Invariant to the number of fused ranked lists (no
2686
+ # hardcoded multiplier).
2687
+ if not results:
2688
+ fts_results = self.tortoise_fts_query(q, limit=limit)
2689
+ results = []
2690
+ max_rrf = max(
2691
+ (r.get("scores", {}).get("rrf", 0.0) for r in fts_results),
2692
+ default=0.0,
2693
+ )
2694
+ # No fusion signal at all (max_rrf == 0, e.g. TF-IDF fallback with
2695
+ # all-zero similarity) → return NOTHING: every result would carry
2696
+ # confidence 0.0, which is indistinguishable from 'no match' and
2697
+ # pollutes suggest_entry_points with decoys for garbage queries
2698
+ # (stale test #test_no_match_returns_empty).
2699
+ if max_rrf <= 0:
2700
+ return []
2701
+ for r in fts_results:
2702
+ rrf = r.get("scores", {}).get("rrf", 0.0)
2703
+ confidence = round(0.49 * rrf / max_rrf, 4)
2704
+ results.append({"id": r["id"], "name": r.get("content", ""),
2705
+ "kind": r.get("point_kind", ""), "confidence": confidence})
2706
+ results.sort(key=lambda r: r["confidence"], reverse=True)
2707
+
2708
+ # #25: optional graph-informed rerank (persisted EP confidence,
2709
+ # operator connectivity, recency). Off by default (backward compat).
2710
+ if graph_ranker is not None and results:
2711
+ results = graph_ranker.rerank(results, entity_type="point")
2712
+
2713
+ return results
2714
+
2715
+ # ── Session Context (#6989) ──────────────────────────────
2716
+
2717
+ def session_context(self) -> dict:
2718
+ """Return 'what happened last session' — diary entries, Points, Events, confidence changes.
2719
+ Returns structured dict with explicit 'no_prior_sessions' when graph is empty."""
2720
+ proj = self._get_proj()
2721
+ diary_entries = [r[0] for r in proj.g.query(
2722
+ "MATCH (n:Point {pointKind:'diary'}) "
2723
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2724
+ "RETURN properties(n) ORDER BY n.createdAt DESC LIMIT 10"
2725
+ ).result_set]
2726
+ recent_points = [r[0] for r in proj.g.query(
2727
+ "MATCH (n:Point) "
2728
+ "WHERE (n.is_operator IS NULL OR n.is_operator = false) "
2729
+ "RETURN properties(n) ORDER BY n.createdAt DESC LIMIT 20"
2730
+ ).result_set]
2731
+ recent_events = [r[0] for r in proj.g.query(
2732
+ "MATCH (e:Event) RETURN properties(e) ORDER BY e.startedAt DESC LIMIT 20"
2733
+ ).result_set]
2734
+ confidence_changes = [
2735
+ {"id": r[0], "content": r[1], "pointKind": r[2],
2736
+ "confidence": r[3], "updatedAt": r[4]}
2737
+ for r in proj.g.query(
2738
+ "MATCH (n:Point) WHERE n.confidence IS NOT NULL "
2739
+ "AND (n.is_operator IS NULL OR n.is_operator = false) "
2740
+ "RETURN n.id, n.content, n.pointKind, n.confidence, n.updatedAt "
2741
+ "ORDER BY n.updatedAt DESC LIMIT 20"
2742
+ ).result_set
2743
+ ]
2744
+ no_prior = not diary_entries and not recent_points and not recent_events
2745
+ return {
2746
+ "no_prior_sessions": no_prior,
2747
+ "diary_entries": diary_entries,
2748
+ "recent_points": recent_points,
2749
+ "recent_events": recent_events,
2750
+ "confidence_changes": confidence_changes,
2751
+ }
2752
+
2753
+ # ── Hybrid Search (Phase 0, #7748) ───────────────────────────
2754
+
2755
+ def tortoise_fts_query(
2756
+ self,
2757
+ query: str | None = None,
2758
+ kind: str | None = None,
2759
+ *,
2760
+ entity_type: str = "point",
2761
+ min_confidence: float = 0.0,
2762
+ order_by: str = "relevance",
2763
+ graph_ranker=None,
2764
+ limit: int = 10,
2765
+ threshold: float = 0.0,
2766
+ relationship_filter: str | None = None,
2767
+ traversal_path: str | None = None,
2768
+ ) -> list[dict]:
2769
+ """Hybrid search with RRF fusion + EP annotation.
2770
+
2771
+ entity_type: 'point' (default), 'event', 'subject', 'document', 'object', 'operator', or 'source'.
2772
+ Full-scan mode: omit query, set kind → all Points of that kind.
2773
+ Best-match mode: provide query → RRF fusion of FTS + vector + structural.
2774
+
2775
+ Point results annotated with EP breakdown (confidence_mean + evidence + contention).
2776
+ Non-Point entities skip EP annotation.
2777
+ min_confidence defaults to 0.0 (no filter).
2778
+
2779
+ relationship_filter: 'predicate:target_id' — only return points connected to
2780
+ target_id via an operator with label=predicate (e.g., 'addresses:customerSegment-1').
2781
+ traversal_path: 'FromKind→ToKind' — only return points that participate in a
2782
+ pack-declared relation chain (e.g., 'Product→Feature'). Resolved via pack registry.
2783
+ """
2784
+ from .search_engine import (
2785
+ classify_query, degradation_chain, rrf_fusion,
2786
+ annotate_ep_batch, get_relationships, fallback_tfidf,
2787
+ SearchResult, SearchScores,
2788
+ filter_by_relationship, filter_by_traversal_predicate,
2789
+ )
2790
+
2791
+ if entity_type not in ("point", "event", "subject", "document", "object", "operator", "source"):
2792
+ raise ValueError(f"entity_type must be 'point', 'event', 'subject', 'document', 'object', 'operator', or 'source', got {entity_type!r}")
2793
+ if limit < 1 or limit > 10000:
2794
+ raise ValueError(f"limit must be 1-10000, got {limit}")
2795
+ if not (0.0 <= threshold <= 1.0):
2796
+ raise ValueError(f"threshold must be 0.0-1.0, got {threshold}")
2797
+ if not (0.0 <= min_confidence <= 1.0):
2798
+ raise ValueError(f"min_confidence must be 0.0-1.0, got {min_confidence}")
2799
+ if order_by not in ("relevance", "confidence", "graph"):
2800
+ raise ValueError(f"order_by must be 'relevance', 'confidence', or 'graph', got {order_by!r}")
2801
+
2802
+ proj = self._get_proj()
2803
+ graph = proj.g
2804
+ label = entity_type.capitalize() # point→Point, event→Event, subject→Subject
2805
+ # Operator: Point nodes with is_operator=true, kind=op_type
2806
+ # Source: Source nodes, kind=sourceKind
2807
+ kind_field = {"point": "pointKind", "event": "eventKind", "subject": "subjectKind", "document": "documentKind", "object": "objectKind", "operator": "op_type", "source": "sourceKind"}[entity_type]
2808
+
2809
+ # 1. Classify query → determine active strategies
2810
+ strategies = classify_query(query, kind)
2811
+ is_full_scan = (query is None and kind is not None)
2812
+
2813
+ # Expand kind early for pack-aware structural query + kind filter
2814
+ expanded_kinds = self._expand_kind(kind) if kind else None
2815
+
2816
+ # 2. Get query vector if needed (all core entity types now have embeddings #7845)
2817
+ query_vec = None
2818
+ if strategies.get("vector") and query and query.strip():
2819
+ try:
2820
+ from .embeddings import EmbeddingModel
2821
+ model = EmbeddingModel.get()
2822
+ if model:
2823
+ query_vec = model.encode([query])[0].tolist()
2824
+ except Exception:
2825
+ pass # Graceful — vector strategy will degrade
2826
+
2827
+ # 3. Run retrieval with degradation
2828
+ is_embedded = getattr(proj, '_is_embedded', True)
2829
+ # Full-scan mode: no truncation — return ALL Points in context (#7811 completeness)
2830
+ str_limit = limit * 2 if not is_full_scan else 100000
2831
+ raw_results = degradation_chain(
2832
+ graph, query, kind, query_vec, strategies,
2833
+ entity_type=entity_type, limit=str_limit,
2834
+ is_embedded=is_embedded,
2835
+ )
2836
+
2837
+ if not raw_results:
2838
+ # All strategies failed — fallback to in-memory TF-IDF (Point only)
2839
+ if query and entity_type == "point":
2840
+ points = self.query(kind=kind)
2841
+ return fallback_tfidf(query, points, limit=limit)
2842
+ return []
2843
+
2844
+ # 4. Fuse via RRF (skip if single strategy or full-scan)
2845
+ if is_full_scan or len(raw_results) == 1:
2846
+ strat_name, ranked = next(iter(raw_results.items()))
2847
+ # Apply threshold filter (score floor)
2848
+ fused = {pid: score for pid, score in ranked if score >= threshold}
2849
+ match_source = strat_name
2850
+ else:
2851
+ ranked_lists = list(raw_results.values())
2852
+ fused = rrf_fusion(ranked_lists)
2853
+ # Apply threshold filter to RRF scores
2854
+ if threshold > 0:
2855
+ fused = {pid: score for pid, score in fused.items() if score >= threshold}
2856
+ match_source = "rrf"
2857
+
2858
+ # 5. Apply kind filter BEFORE truncating (skip if structural-only already filtered)
2859
+ result_ids = list(fused.keys())
2860
+ if entity_type == "source":
2861
+ id_field = "url"
2862
+ elif entity_type == "event":
2863
+ id_field = "eventId"
2864
+ else:
2865
+ id_field = "id"
2866
+ # Graph label for MATCH (operators are Point nodes with is_operator=true)
2867
+ graph_label = "Point" if entity_type == "operator" else label
2868
+
2869
+ if kind and query is not None and result_ids:
2870
+ expanded = expanded_kinds
2871
+ kind_ids = set()
2872
+ extra_clause = "AND n.is_operator = true" if entity_type == "operator" else ""
2873
+ try:
2874
+ if len(expanded) == 1:
2875
+ kind_rows = graph.query(
2876
+ f"MATCH (n:{graph_label}) WHERE n.{kind_field} = $kind {extra_clause} AND n.{id_field} IN $ids RETURN n.{id_field}",
2877
+ params={"kind": expanded[0], "ids": result_ids},
2878
+ ).result_set
2879
+ else:
2880
+ placeholders = [f"$kind_{i}" for i in range(len(expanded))]
2881
+ params_dict: dict[str, Any] = {"ids": result_ids}
2882
+ for i, k in enumerate(expanded):
2883
+ params_dict[f"kind_{i}"] = k
2884
+ kind_rows = graph.query(
2885
+ f"MATCH (n:{graph_label}) WHERE n.{kind_field} IN [{', '.join(placeholders)}] {extra_clause} AND n.{id_field} IN $ids RETURN n.{id_field}",
2886
+ params=params_dict,
2887
+ ).result_set
2888
+ kind_ids = {row[0] for row in kind_rows}
2889
+ except Exception:
2890
+ kind_ids = set(result_ids) # Pass-through on error
2891
+ result_ids = [pid for pid in result_ids if pid in kind_ids]
2892
+
2893
+ # 5b. Apply relationship_filter (predicate:target_id format)
2894
+ if relationship_filter and result_ids:
2895
+ parts = relationship_filter.split(":", 1)
2896
+ if len(parts) == 2:
2897
+ pred, tid = parts[0].strip(), parts[1].strip()
2898
+ if pred and tid:
2899
+ result_ids = filter_by_relationship(
2900
+ graph, result_ids, pred, tid,
2901
+ entity_type=entity_type, id_field=id_field,
2902
+ )
2903
+ else:
2904
+ _logger.warning("Invalid relationship_filter format: %s", relationship_filter)
2905
+ else:
2906
+ _logger.warning(
2907
+ "relationship_filter must be 'predicate:target_id', got: %s",
2908
+ relationship_filter,
2909
+ )
2910
+
2911
+ # 5c. Apply traversal_path (e.g., 'Product→Feature') — resolve via pack registry
2912
+ if traversal_path and result_ids:
2913
+ resolved = self._resolve_traversal_path(traversal_path)
2914
+ if resolved:
2915
+ pred = resolved["predicate"]
2916
+ result_ids = filter_by_traversal_predicate(
2917
+ graph, result_ids, pred,
2918
+ entity_type=entity_type, id_field=id_field,
2919
+ )
2920
+ else:
2921
+ _logger.warning(
2922
+ "traversal_path %r could not be resolved to a pack relation",
2923
+ traversal_path,
2924
+ )
2925
+
2926
+ # Truncate AFTER filtering
2927
+ result_ids = result_ids[:limit]
2928
+
2929
+ # 6. EP annotation (Point only)
2930
+ ep_breakdowns = annotate_ep_batch(graph, result_ids) if entity_type == "point" else {}
2931
+
2932
+ # 7. Fetch entity content in BATCH (not N+1)
2933
+ entity_data: dict[str, dict] = {}
2934
+ try:
2935
+ if entity_type == "point":
2936
+ rows = graph.query(
2937
+ "MATCH (n:Point) WHERE n.id IN $ids RETURN n.id, n.content, n.pointKind",
2938
+ params={"ids": result_ids},
2939
+ ).result_set
2940
+ for row in rows:
2941
+ pid = row[0]
2942
+ entity_data[pid] = {
2943
+ "content": row[1],
2944
+ "kind": row[2],
2945
+ }
2946
+ elif entity_type == "event":
2947
+ rows = graph.query(
2948
+ "MATCH (n:Event) WHERE n.eventId IN $ids RETURN n.eventId, n.subject, n.eventKind",
2949
+ params={"ids": result_ids},
2950
+ ).result_set
2951
+ for row in rows:
2952
+ eid = row[0]
2953
+ entity_data[eid] = {
2954
+ "content": row[1] or "",
2955
+ "kind": row[2] or "",
2956
+ }
2957
+ elif entity_type == "subject":
2958
+ rows = graph.query(
2959
+ "MATCH (n:Subject) WHERE n.id IN $ids RETURN n.id, n.name, n.subjectKind",
2960
+ params={"ids": result_ids},
2961
+ ).result_set
2962
+ for row in rows:
2963
+ sid = row[0]
2964
+ entity_data[sid] = {
2965
+ "content": row[1] or "",
2966
+ "kind": row[2] or "",
2967
+ }
2968
+ elif entity_type == "document":
2969
+ rows = graph.query(
2970
+ "MATCH (n:Document) WHERE n.id IN $ids "
2971
+ "RETURN n.id, n.title, n.documentKind, n.topics, n.summary, "
2972
+ "n.sessionId, n.eventId, n.sourcePath",
2973
+ params={"ids": result_ids},
2974
+ ).result_set
2975
+ for row in rows:
2976
+ did = row[0]
2977
+ entity_data[did] = {
2978
+ "content": row[1] or "",
2979
+ "kind": row[2] or "",
2980
+ "topics": row[3] or [],
2981
+ "summary": row[4] or "",
2982
+ "sessionId": row[5] or "",
2983
+ "eventId": row[6] or "",
2984
+ "sourcePath": row[7] or "" if len(row) > 7 else "",
2985
+ }
2986
+ elif entity_type == "object":
2987
+ rows = graph.query(
2988
+ "MATCH (n:Object) WHERE n.id IN $ids RETURN n.id, n.name, n.objectKind",
2989
+ params={"ids": result_ids},
2990
+ ).result_set
2991
+ for row in rows:
2992
+ oid = row[0]
2993
+ entity_data[oid] = {
2994
+ "content": row[1] or "",
2995
+ "kind": row[2] or "",
2996
+ }
2997
+ elif entity_type == "operator":
2998
+ rows = graph.query(
2999
+ "MATCH (n:Point {is_operator: true}) WHERE n.id IN $ids RETURN n.id, n.label, n.op_type",
3000
+ params={"ids": result_ids},
3001
+ ).result_set
3002
+ for row in rows:
3003
+ oid = row[0]
3004
+ entity_data[oid] = {
3005
+ "content": row[1] or "", # label is searchable text
3006
+ "kind": row[2] or "", # op_type is kind
3007
+ }
3008
+ elif entity_type == "source":
3009
+ rows = graph.query(
3010
+ "MATCH (n:Source) WHERE n.url IN $ids RETURN n.url, n.title, n.sourceKind",
3011
+ params={"ids": result_ids},
3012
+ ).result_set
3013
+ for row in rows:
3014
+ sid = row[0]
3015
+ entity_data[sid] = {
3016
+ "content": row[1] or "",
3017
+ "kind": row[2] or "",
3018
+ }
3019
+ except Exception:
3020
+ _logger.warning("Batch content fetch failed — returning results with minimal metadata")
3021
+ for pid in result_ids:
3022
+ entity_data[pid] = {"content": "", "kind": ""}
3023
+
3024
+ # 7.5. Fetch relationships for result Points (Point only)
3025
+ point_relationships = get_relationships(graph, result_ids) if entity_type == "point" else {}
3026
+
3027
+ # 8. Build SearchResult objects, filter, and order
3028
+ results = []
3029
+ for pid in result_ids:
3030
+ pt = entity_data.get(pid)
3031
+ if not pt:
3032
+ continue
3033
+ content, pt_kind = pt["content"], pt["kind"]
3034
+ ep = ep_breakdowns.get(pid) if entity_type == "point" else None
3035
+ # #125 capture metadata (document entity_type)
3036
+ cap_topics = pt.get("topics", [])
3037
+ cap_summary = pt.get("summary", "")
3038
+ cap_session = pt.get("sessionId", "")
3039
+ cap_event = pt.get("eventId", "")
3040
+ cap_source_path = pt.get("sourcePath", "") # #167
3041
+
3042
+ # Apply min_confidence filter (Point only; non-Point always pass)
3043
+ if entity_type == "point" and ep and ep.confidence_mean < min_confidence:
3044
+ continue
3045
+
3046
+ # Build scores
3047
+ scores = SearchScores(rrf=fused.get(pid, 0.0))
3048
+ if "fts" in raw_results:
3049
+ for fid, fscore in raw_results["fts"]:
3050
+ if fid == pid:
3051
+ scores.fts = fscore
3052
+ break
3053
+ if "vector" in raw_results:
3054
+ for vid, vscore in raw_results["vector"]:
3055
+ if vid == pid:
3056
+ scores.vector = vscore
3057
+ break
3058
+ if "structural" in raw_results:
3059
+ for sid, sscore in raw_results["structural"]:
3060
+ if sid == pid:
3061
+ scores.structural = sscore
3062
+ break
3063
+
3064
+ result = SearchResult(
3065
+ id=pid,
3066
+ content=content,
3067
+ point_kind=pt_kind,
3068
+ scores=scores,
3069
+ match_source=match_source,
3070
+ ep=ep,
3071
+ relationships=point_relationships.get(pid, []),
3072
+ topics=cap_topics,
3073
+ summary=cap_summary,
3074
+ session_id=cap_session,
3075
+ event_id=cap_event,
3076
+ source_path=cap_source_path,
3077
+ )
3078
+ results.append(result)
3079
+
3080
+ # 9. Order results
3081
+ if order_by == "graph":
3082
+ # #25: graph-informed rerank — weighted fusion of similarity +
3083
+ # persisted EP confidence + operator connectivity + recency decay.
3084
+ # Requires the caller to allow a large enough candidate pool (limit
3085
+ # here is the pool size; final length is capped below).
3086
+ from .ranking import GraphRanker
3087
+ ranker = graph_ranker or GraphRanker(proj)
3088
+ dicts = [r.to_dict() for r in results]
3089
+ return ranker.rerank(dicts, entity_type=entity_type)[:limit]
3090
+ if order_by == "confidence":
3091
+ # #25: sort by the PERSISTED EP confidence (n.confidence, written
3092
+ # by compute_confidence), not the structural impl/(impl+nand) proxy
3093
+ # from annotate_ep_batch (which is edge-ratio, not belief).
3094
+ from .ranking import GraphRanker
3095
+ ranker = graph_ranker or GraphRanker(proj)
3096
+ signals = ranker._fetch_signals([r.id for r in results], entity_type)
3097
+ results.sort(
3098
+ key=lambda r: signals.get(r.id, {}).get("confidence", 0.5),
3099
+ reverse=True,
3100
+ )
3101
+ # Default: RRF relevance order (already in fused order)
3102
+
3103
+ return [r.to_dict() for r in results[:limit]]
3104
+
3105
+ # ── Multi-tenancy (#7001) ─────────────────────────────────
3106
+
3107
+ # ── Control Plane: Team CRUD ───────────────────────────────────
3108
+
3109
+ def team_create(self, name: str, *, idempotency_key: str | None = None) -> dict:
3110
+ """Create a team with its own graph namespace.
3111
+
3112
+ Writes to the control_plane registry graph. Creates a tenant
3113
+ graph (team_{name}) for Point/Operator storage.
3114
+
3115
+ Returns {name, graph_name, api_key, id}.
3116
+ """
3117
+ import re, uuid
3118
+ from datetime import datetime, timezone
3119
+ from tortoise.auth import hash_api_key
3120
+ from .exceptions import ControlPlaneError
3121
+
3122
+ # Input validation
3123
+ if not name or not name.strip():
3124
+ raise ControlPlaneError("Team name must not be empty")
3125
+ if len(name) > 64:
3126
+ raise ControlPlaneError("Team name must be 64 characters or fewer")
3127
+ if not re.match(r'^[a-zA-Z0-9][a-zA-Z0-9_-]*$', name):
3128
+ raise ControlPlaneError(
3129
+ f"Invalid team name: {name!r}. Use alphanumeric, hyphens, underscores."
3130
+ )
3131
+
3132
+ api_key = f"tt_{uuid.uuid4().hex}"
3133
+ key_hash = hash_api_key(api_key)
3134
+ graph_name = f"team_{name}"
3135
+ proj = self._get_proj()
3136
+ reg = self._get_registry()
3137
+ now = datetime.now(timezone.utc).isoformat()
3138
+
3139
+ # Idempotency — check registry graph for existing team
3140
+ if idempotency_key:
3141
+ existing = reg.query(
3142
+ "MATCH (t:Team {idempotency_key:$ik}) RETURN t.id, t.name",
3143
+ params={"ik": idempotency_key},
3144
+ ).result_set
3145
+ if existing:
3146
+ row = existing[0]
3147
+ return {"name": name, "graph_name": graph_name,
3148
+ "api_key": api_key, "id": row[0],
3149
+ "existing": True}
3150
+
3151
+ # Duplicate name check
3152
+ dup = reg.query(
3153
+ "MATCH (t:Team {name:$name}) RETURN count(t) > 0",
3154
+ params={"name": name},
3155
+ ).result_set[0][0]
3156
+ if dup:
3157
+ raise ControlPlaneError(f"Team {name!r} already exists")
3158
+
3159
+ tid = ulid()
3160
+ reg.query(
3161
+ "CREATE (t:Team {id:$id, name:$name, api_key:$key, "
3162
+ "graph_name:$gn, createdAt:$now, tier:'free'})",
3163
+ params={"id": tid, "name": name, "key": key_hash,
3164
+ "gn": graph_name, "now": now},
3165
+ )
3166
+ if idempotency_key:
3167
+ reg.query(
3168
+ "MATCH (t:Team {id:$id}) SET t.idempotency_key = $ik",
3169
+ params={"id": tid, "ik": idempotency_key},
3170
+ )
3171
+ try:
3172
+ team_graph = proj.db.select_graph(graph_name)
3173
+ team_graph.query(
3174
+ "CREATE (:TeamMeta {name:$name, created:$now})",
3175
+ params={"name": name, "now": now},
3176
+ )
3177
+ except Exception:
3178
+ try:
3179
+ reg.query("MATCH (t:Team {id:$id}) DETACH DELETE t",
3180
+ params={"id": tid})
3181
+ except Exception:
3182
+ pass
3183
+ raise
3184
+
3185
+ self._audit(tid, None, "team_create", resource_type="team", resource_id=tid)
3186
+ return {"name": name, "graph_name": graph_name, "api_key": api_key, "id": tid}
3187
+
3188
+ def team_get(self, team_id: str) -> dict | None:
3189
+ """Get a team by ID. Returns None if not found."""
3190
+ reg = self._get_registry()
3191
+ rows = reg.query(
3192
+ "MATCH (t:Team {id:$id}) RETURN properties(t)",
3193
+ params={"id": team_id},
3194
+ ).result_set
3195
+ return rows[0][0] if rows else None
3196
+
3197
+ def team_list(self) -> list[dict]:
3198
+ """List all teams."""
3199
+ reg = self._get_registry()
3200
+ rows = reg.query(
3201
+ "MATCH (t:Team) RETURN properties(t) ORDER BY t.createdAt"
3202
+ ).result_set
3203
+ return [r[0] for r in rows]
3204
+
3205
+ def team_update(self, team_id: str, **fields) -> dict:
3206
+ """Update mutable team fields."""
3207
+ from .exceptions import ControlPlaneError
3208
+ allowed = {
3209
+ "name", "tier", "stripe_customer_id", "subscription_id",
3210
+ "backup_enabled", "max_users", "max_teams", "max_graphs",
3211
+ # #329 relief path: quota limits settable via the control plane so
3212
+ # a team at cap can be upgraded (no REST surface exists yet — the
3213
+ # fields are SDK/registry-level; get_current_team honors them).
3214
+ "max_points", "max_api_keys", "max_sessions",
3215
+ }
3216
+ invalid = set(fields.keys()) - allowed
3217
+ if invalid:
3218
+ raise ControlPlaneError(f"Invalid team fields: {invalid}")
3219
+ reg = self._get_registry()
3220
+ reg.query(
3221
+ "MATCH (t:Team {id:$id}) SET t += $fields",
3222
+ params={"id": team_id, "fields": fields},
3223
+ )
3224
+ self._audit(team_id, None, "team_update", resource_type="team",
3225
+ resource_id=team_id)
3226
+ return self.team_get(team_id) or {}
3227
+
3228
+ def team_delete(self, team_id: str, *, confirmation: str) -> dict:
3229
+ """Delete a team and all associated control-plane entities.
3230
+
3231
+ Cascading: Membership, APIKey, Invitation nodes are deleted.
3232
+ Tenant graphs are dropped (best-effort — FalkorDBLite may skip).
3233
+ Postgres audit_events are preserved (immutable).
3234
+
3235
+ Requires confirmation matching the team name.
3236
+ """
3237
+ from .exceptions import ControlPlaneError
3238
+ team = self.team_get(team_id)
3239
+ if team is None:
3240
+ raise ControlPlaneError(f"Team {team_id!r} not found")
3241
+ if confirmation != team.get("name", ""):
3242
+ raise ControlPlaneError(
3243
+ "Confirmation must match team name exactly"
3244
+ )
3245
+
3246
+ reg = self._get_registry()
3247
+ # Cascade delete: Membership, APIKey, Invitation
3248
+ reg.query(
3249
+ "MATCH (m:Membership {team_id:$tid}) DETACH DELETE m",
3250
+ params={"tid": team_id},
3251
+ )
3252
+ reg.query(
3253
+ "MATCH (k:APIKey {team_id:$tid}) DETACH DELETE k",
3254
+ params={"tid": team_id},
3255
+ )
3256
+ reg.query(
3257
+ "MATCH (i:Invitation {team_id:$tid}) DETACH DELETE i",
3258
+ params={"tid": team_id},
3259
+ )
3260
+ reg.query(
3261
+ "MATCH (t:Team {id:$id}) DETACH DELETE t",
3262
+ params={"id": team_id},
3263
+ )
3264
+
3265
+ # Best-effort tenant graph deletion
3266
+ graph_name = team.get("graph_name", f"team_{team.get('name', '')}")
3267
+ proj = self._get_proj()
3268
+ try:
3269
+ if hasattr(proj.db, 'delete_graph'):
3270
+ proj.db.delete_graph(graph_name)
3271
+ else:
3272
+ _logger.debug("delete_graph not available (FalkorDBLite) — skipping")
3273
+ except Exception:
3274
+ _logger.debug("Failed to delete tenant graph %s — skipping", graph_name)
3275
+
3276
+ self._audit(team_id, None, "team_delete", resource_type="team",
3277
+ resource_id=team_id)
3278
+ return {"deleted": True, "team_id": team_id}
3279
+
3280
+ def migrate_teams_to_registry(self) -> dict:
3281
+ """One-shot: move Team nodes from tortoise graph to control_plane graph.
3282
+
3283
+ Idempotent — running twice produces the same state.
3284
+ Existing Team nodes in the tortoise graph are marked as outdated.
3285
+ """
3286
+ proj = self._get_proj()
3287
+ reg = self._get_registry()
3288
+ teams = proj.g.query("MATCH (t:Team) RETURN properties(t)").result_set
3289
+ migrated, skipped = 0, 0
3290
+ for row in teams:
3291
+ team = row[0]
3292
+ name = team.get("name", "")
3293
+ # Check if already in registry
3294
+ existing = reg.query(
3295
+ "MATCH (t:Team {name:$name}) RETURN count(t) > 0",
3296
+ params={"name": name},
3297
+ ).result_set[0][0]
3298
+ if existing:
3299
+ skipped += 1
3300
+ continue
3301
+ reg.query(
3302
+ "CREATE (t:Team {id:$id, name:$name, api_key:$key, "
3303
+ "graph_name:$gn, createdAt:$now})",
3304
+ params={
3305
+ "id": team.get("id", ulid()),
3306
+ "name": name,
3307
+ "key": team.get("api_key", ""),
3308
+ "gn": team.get("graph_name", f"team_{name}"),
3309
+ "now": team.get("createdAt", ""),
3310
+ },
3311
+ )
3312
+ migrated += 1
3313
+ if migrated > 0:
3314
+ proj.g.query("MATCH (t:Team) SET t.status = 'outdated'")
3315
+ return {"migrated": migrated, "skipped": skipped}
3316
+
3317
+ # ── Control Plane: Membership CRUD ─────────────────────────────
3318
+
3319
+ def membership_create(self, team_id: str, user_id: str, role: str) -> dict:
3320
+ """Add a user to a team with a given role.
3321
+
3322
+ Validates role, team existence, and max_users constraint.
3323
+ Creates BELONGS_TO edge to Team.
3324
+ """
3325
+ from datetime import datetime, timezone
3326
+ from .exceptions import ControlPlaneError
3327
+
3328
+ if role not in ("owner", "admin"):
3329
+ raise ControlPlaneError(
3330
+ f"Invalid role {role!r}. Must be 'owner' or 'admin'."
3331
+ )
3332
+
3333
+ team = self.team_get(team_id)
3334
+ if team is None:
3335
+ raise ControlPlaneError(f"Team {team_id!r} not found")
3336
+
3337
+ # Check max_users constraint
3338
+ max_users = team.get("max_users")
3339
+ if max_users is not None:
3340
+ reg = self._get_registry()
3341
+ count = reg.query(
3342
+ "MATCH (m:Membership {team_id:$tid}) RETURN count(m)",
3343
+ params={"tid": team_id},
3344
+ ).result_set[0][0]
3345
+ if count >= max_users:
3346
+ raise ControlPlaneError(
3347
+ f"Team at max users ({max_users}). Upgrade to add more."
3348
+ )
3349
+
3350
+ mid = ulid()
3351
+ now = datetime.now(timezone.utc).isoformat()
3352
+ reg = self._get_registry()
3353
+ reg.query(
3354
+ "CREATE (m:Membership {id:$id, user_id:$uid, team_id:$tid, "
3355
+ "role:$role, joinedAt:$now})",
3356
+ params={"id": mid, "uid": user_id, "tid": team_id,
3357
+ "role": role, "now": now},
3358
+ )
3359
+ # Create BELONGS_TO edge
3360
+ reg.query(
3361
+ "MATCH (m:Membership {id:$mid}), (t:Team {id:$tid}) "
3362
+ "CREATE (m)-[:BELONGS_TO]->(t)",
3363
+ params={"mid": mid, "tid": team_id},
3364
+ )
3365
+
3366
+ self._audit(team_id, user_id, "membership_create",
3367
+ resource_type="membership", resource_id=mid)
3368
+ return {"id": mid, "team_id": team_id, "user_id": user_id, "role": role}
3369
+
3370
+ def membership_get(self, membership_id: str) -> dict | None:
3371
+ """Get a membership by ID."""
3372
+ reg = self._get_registry()
3373
+ rows = reg.query(
3374
+ "MATCH (m:Membership {id:$id}) RETURN properties(m)",
3375
+ params={"id": membership_id},
3376
+ ).result_set
3377
+ return rows[0][0] if rows else None
3378
+
3379
+ def membership_list(self, team_id: str) -> list[dict]:
3380
+ """List all memberships for a team."""
3381
+ reg = self._get_registry()
3382
+ rows = reg.query(
3383
+ "MATCH (m:Membership {team_id:$tid}) RETURN properties(m)",
3384
+ params={"tid": team_id},
3385
+ ).result_set
3386
+ return [r[0] for r in rows]
3387
+
3388
+ def membership_update_role(self, membership_id: str,
3389
+ new_role: str) -> dict:
3390
+ """Update a membership's role."""
3391
+ from .exceptions import ControlPlaneError
3392
+ if new_role not in ("owner", "admin"):
3393
+ raise ControlPlaneError(
3394
+ f"Invalid role {new_role!r}. Must be 'owner' or 'admin'."
3395
+ )
3396
+ m = self.membership_get(membership_id)
3397
+ if m is None:
3398
+ raise ControlPlaneError(f"Membership {membership_id!r} not found")
3399
+ reg = self._get_registry()
3400
+ reg.query(
3401
+ "MATCH (m:Membership {id:$id}) SET m.role = $role",
3402
+ params={"id": membership_id, "role": new_role},
3403
+ )
3404
+ self._audit(m["team_id"], m["user_id"], "membership_update_role",
3405
+ resource_type="membership", resource_id=membership_id)
3406
+ return self.membership_get(membership_id) or {}
3407
+
3408
+ def membership_delete(self, membership_id: str) -> dict:
3409
+ """Delete a membership. Idempotent."""
3410
+ m = self.membership_get(membership_id)
3411
+ if m is None:
3412
+ return {"deleted": False, "reason": "not found"}
3413
+ reg = self._get_registry()
3414
+ reg.query(
3415
+ "MATCH (m:Membership {id:$id}) DETACH DELETE m",
3416
+ params={"id": membership_id},
3417
+ )
3418
+ self._audit(m["team_id"], m["user_id"], "membership_delete",
3419
+ resource_type="membership", resource_id=membership_id)
3420
+ return {"deleted": True, "membership_id": membership_id}
3421
+
3422
+ # ── Control Plane: APIKey CRUD ─────────────────────────────────
3423
+
3424
+ def _verify_hashed_lookup(self, label: str, prop: str, plaintext: str) -> list[dict]:
3425
+ """Verify a plaintext secret against stored salted hashes in the registry.
3426
+
3427
+ hash_api_key() embeds a per-key random salt ("salt:hash"), so we can
3428
+ NOT look up by exact hash match — the lookup hash would never equal the
3429
+ stored hash (same root cause as #130). Instead fetch all candidate
3430
+ rows of the label and verify each stored hash against the plaintext.
3431
+ The registry is small (teams × keys × invites), so a scan is fine.
3432
+ """
3433
+ from tortoise.auth import verify_api_key
3434
+ reg = self._get_registry()
3435
+ rows = reg.query(
3436
+ f"MATCH (n:{label}) RETURN n.{prop}, properties(n)"
3437
+ ).result_set
3438
+ out = []
3439
+ for stored_hash, props in rows:
3440
+ if verify_api_key(plaintext, stored_hash):
3441
+ out.append(props)
3442
+ return out
3443
+
3444
+ def apikey_create(self, team_id: str, created_by: str) -> dict:
3445
+ """Generate an API key for a team.
3446
+
3447
+ Stores SHA-256 hash (never plaintext). Plaintext returned once.
3448
+ """
3449
+ import uuid
3450
+ from datetime import datetime, timezone
3451
+ from tortoise.auth import hash_api_key
3452
+ from .exceptions import ControlPlaneError
3453
+
3454
+ team = self.team_get(team_id)
3455
+ if team is None:
3456
+ raise ControlPlaneError(f"Team {team_id!r} not found")
3457
+
3458
+ api_key = f"tt_{uuid.uuid4().hex}"
3459
+ key_hash = hash_api_key(api_key)
3460
+ key_prefix = api_key[:10]
3461
+ kid = ulid()
3462
+ now = datetime.now(timezone.utc).isoformat()
3463
+
3464
+ reg = self._get_registry()
3465
+ reg.query(
3466
+ "CREATE (k:APIKey {id:$id, team_id:$tid, key_hash:$kh, "
3467
+ "key_prefix:$kp, created_by:$cb, created_at:$now})",
3468
+ params={"id": kid, "tid": team_id, "kh": key_hash,
3469
+ "kp": key_prefix, "cb": created_by, "now": now},
3470
+ )
3471
+ # BELONGS_TO edge
3472
+ reg.query(
3473
+ "MATCH (k:APIKey {id:$kid}), (t:Team {id:$tid}) "
3474
+ "CREATE (k)-[:BELONGS_TO]->(t)",
3475
+ params={"kid": kid, "tid": team_id},
3476
+ )
3477
+
3478
+ self._audit(team_id, created_by, "apikey_create",
3479
+ resource_type="apikey", resource_id=kid)
3480
+ return {"id": kid, "key_prefix": key_prefix, "api_key": api_key,
3481
+ "team_id": team_id, "created_at": now}
3482
+
3483
+ def apikey_list(self, team_id: str) -> list[dict]:
3484
+ """List API keys for a team (no plaintext or hashes)."""
3485
+ reg = self._get_registry()
3486
+ rows = reg.query(
3487
+ "MATCH (k:APIKey {team_id:$tid}) "
3488
+ "RETURN k.id, k.key_prefix, k.created_by, k.created_at, "
3489
+ "k.last_used_at, k.revoked_at",
3490
+ params={"tid": team_id},
3491
+ ).result_set
3492
+ keys = []
3493
+ for r in rows:
3494
+ keys.append({
3495
+ "id": r[0], "key_prefix": r[1], "created_by": r[2],
3496
+ "created_at": r[3], "last_used_at": r[4], "revoked_at": r[5],
3497
+ })
3498
+ return keys
3499
+
3500
+ def apikey_revoke(self, key_id: str) -> dict:
3501
+ """Revoke an API key (soft delete — sets revoked_at). Idempotent."""
3502
+ from datetime import datetime, timezone
3503
+ reg = self._get_registry()
3504
+ rows = reg.query(
3505
+ "MATCH (k:APIKey {id:$id}) RETURN k.revoked_at, k.team_id",
3506
+ params={"id": key_id},
3507
+ ).result_set
3508
+ if not rows:
3509
+ return {"revoked": False, "reason": "not found"}
3510
+ if rows[0][0] is not None:
3511
+ return {"revoked": True, "already": True, "key_id": key_id}
3512
+ now = datetime.now(timezone.utc).isoformat()
3513
+ reg.query(
3514
+ "MATCH (k:APIKey {id:$id}) SET k.revoked_at = $now",
3515
+ params={"id": key_id, "now": now},
3516
+ )
3517
+ self._audit(rows[0][1], None, "apikey_revoke",
3518
+ resource_type="apikey", resource_id=key_id)
3519
+ return {"revoked": True, "key_id": key_id, "revoked_at": now}
3520
+
3521
+ def apikey_verify(self, key_plaintext: str) -> dict | None:
3522
+ """Verify an API key against stored hashes.
3523
+
3524
+ Returns {team_id, key_id} if valid, None if not found or revoked.
3525
+ Uses salted-hash verification (per-key salt means exact-hash lookup
3526
+ never matches — see #130, #139).
3527
+ """
3528
+ matches = [
3529
+ p for p in self._verify_hashed_lookup("APIKey", "key_hash", key_plaintext)
3530
+ if p.get("revoked_at") is None
3531
+ ]
3532
+ if matches:
3533
+ return {"team_id": matches[0]["team_id"], "key_id": matches[0]["id"]}
3534
+ return None
3535
+
3536
+ # ── Control Plane: Invitation CRUD ─────────────────────────────
3537
+
3538
+ def invitation_create(self, team_id: str, email: str, role: str,
3539
+ created_by: str) -> dict:
3540
+ """Create an invitation with 7-day expiry.
3541
+
3542
+ Token is hashed for storage; plaintext returned once.
3543
+ """
3544
+ import uuid
3545
+ from datetime import datetime, timedelta, timezone
3546
+ from tortoise.auth import hash_api_key
3547
+ from .exceptions import ControlPlaneError
3548
+
3549
+ team = self.team_get(team_id)
3550
+ if team is None:
3551
+ raise ControlPlaneError(f"Team {team_id!r} not found")
3552
+ if role not in ("owner", "admin"):
3553
+ raise ControlPlaneError(
3554
+ f"Invalid role {role!r}. Must be 'owner' or 'admin'."
3555
+ )
3556
+
3557
+ # Reject duplicate pending invitations for same email+team
3558
+ reg = self._get_registry()
3559
+ dup = reg.query(
3560
+ "MATCH (i:Invitation {team_id:$tid, email:$email}) "
3561
+ "WHERE i.accepted_at IS NULL AND (i.status IS NULL OR i.status <> 'revoked') "
3562
+ "RETURN count(i) > 0",
3563
+ params={"tid": team_id, "email": email},
3564
+ ).result_set[0][0]
3565
+ if dup:
3566
+ raise ControlPlaneError(
3567
+ f"Pending invitation already exists for {email} in this team"
3568
+ )
3569
+
3570
+ token = str(uuid.uuid4())
3571
+ token_hash = hash_api_key(token)
3572
+ iid = ulid()
3573
+ now = datetime.now(timezone.utc).isoformat()
3574
+ expires_at = (datetime.now(timezone.utc) + timedelta(days=7)).isoformat()
3575
+
3576
+ reg.query(
3577
+ "CREATE (i:Invitation {id:$id, team_id:$tid, email:$email, "
3578
+ "role:$role, token_hash:$th, created_by:$cb, "
3579
+ "created_at:$now, expires_at:$exp, accepted_at:null})",
3580
+ params={"id": iid, "tid": team_id, "email": email,
3581
+ "role": role, "th": token_hash, "cb": created_by,
3582
+ "now": now, "exp": expires_at},
3583
+ )
3584
+ # FOR_TEAM edge
3585
+ reg.query(
3586
+ "MATCH (i:Invitation {id:$iid}), (t:Team {id:$tid}) "
3587
+ "CREATE (i)-[:FOR_TEAM]->(t)",
3588
+ params={"iid": iid, "tid": team_id},
3589
+ )
3590
+
3591
+ self._audit(team_id, created_by, "invitation_create",
3592
+ resource_type="invitation", resource_id=iid)
3593
+ return {"id": iid, "email": email, "role": role,
3594
+ "expires_at": expires_at, "token": token}
3595
+
3596
+ def invitation_list(self, team_id: str) -> list[dict]:
3597
+ """List invitations for a team (no token hashes)."""
3598
+ reg = self._get_registry()
3599
+ rows = reg.query(
3600
+ "MATCH (i:Invitation {team_id:$tid}) "
3601
+ "RETURN i.id, i.email, i.role, i.created_by, i.created_at, "
3602
+ "i.expires_at, i.accepted_at, i.status",
3603
+ params={"tid": team_id},
3604
+ ).result_set
3605
+ invs = []
3606
+ for r in rows:
3607
+ invs.append({
3608
+ "id": r[0], "email": r[1], "role": r[2],
3609
+ "created_by": r[3], "created_at": r[4],
3610
+ "expires_at": r[5], "accepted_at": r[6], "status": r[7],
3611
+ })
3612
+ return invs
3613
+
3614
+ def invitation_get_by_token(self, token_plaintext: str) -> dict | None:
3615
+ """Look up an invitation by its plaintext token (salted-hash verify)."""
3616
+ matches = self._verify_hashed_lookup("Invitation", "token_hash", token_plaintext)
3617
+ return matches[0] if matches else None
3618
+
3619
+ def invitation_accept(self, invitation_id: str, user_id: str) -> dict:
3620
+ """Accept an invitation and create a membership.
3621
+
3622
+ Checks expiry and single-use (not already accepted).
3623
+ """
3624
+ from datetime import datetime, timezone
3625
+ from .exceptions import ControlPlaneError
3626
+
3627
+ inv = self.invitation_get_by_id(invitation_id)
3628
+ if inv is None:
3629
+ raise ControlPlaneError(f"Invitation {invitation_id!r} not found")
3630
+
3631
+ expires_at = inv.get("expires_at", "")
3632
+ now = datetime.now(timezone.utc)
3633
+ if expires_at:
3634
+ exp = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
3635
+ if now > exp:
3636
+ raise ControlPlaneError("Invitation has expired")
3637
+
3638
+ if inv.get("accepted_at"):
3639
+ raise ControlPlaneError("Invitation already accepted")
3640
+
3641
+ if inv.get("status") == "revoked":
3642
+ raise ControlPlaneError("Invitation has been revoked")
3643
+
3644
+ # Accept: mark as accepted + create membership
3645
+ now_iso = now.isoformat()
3646
+ reg = self._get_registry()
3647
+ reg.query(
3648
+ "MATCH (i:Invitation {id:$id}) SET i.accepted_at = $now",
3649
+ params={"id": invitation_id, "now": now_iso},
3650
+ )
3651
+
3652
+ membership = self.membership_create(
3653
+ team_id=inv["team_id"],
3654
+ user_id=user_id,
3655
+ role=inv.get("role", "admin"),
3656
+ )
3657
+
3658
+ self._audit(inv["team_id"], user_id, "invitation_accept",
3659
+ resource_type="invitation", resource_id=invitation_id)
3660
+ return {"membership_id": membership["id"],
3661
+ "team_id": inv["team_id"], "accepted_at": now_iso}
3662
+
3663
+ def invitation_get_by_id(self, invitation_id: str) -> dict | None:
3664
+ """Get an invitation by its ULID."""
3665
+ reg = self._get_registry()
3666
+ rows = reg.query(
3667
+ "MATCH (i:Invitation {id:$id}) RETURN properties(i)",
3668
+ params={"id": invitation_id},
3669
+ ).result_set
3670
+ return rows[0][0] if rows else None
3671
+
3672
+ def invitation_revoke(self, invitation_id: str) -> dict:
3673
+ """Revoke an invitation (soft delete). Idempotent."""
3674
+ inv = self.invitation_get_by_id(invitation_id)
3675
+ if inv is None:
3676
+ return {"revoked": False, "reason": "not found"}
3677
+ if inv.get("status") == "revoked":
3678
+ return {"revoked": True, "already": True,
3679
+ "invitation_id": invitation_id}
3680
+ reg = self._get_registry()
3681
+ reg.query(
3682
+ "MATCH (i:Invitation {id:$id}) SET i.status = 'revoked'",
3683
+ params={"id": invitation_id},
3684
+ )
3685
+ self._audit(inv["team_id"], None, "invitation_revoke",
3686
+ resource_type="invitation", resource_id=invitation_id)
3687
+ return {"revoked": True, "invitation_id": invitation_id}
3688
+
3689
+ def cleanup_expired_invitations(self) -> dict:
3690
+ """Mark expired invitations as 'expired' status.
3691
+
3692
+ Returns count of cleaned invitations.
3693
+ """
3694
+ from datetime import datetime, timezone
3695
+ now = datetime.now(timezone.utc).isoformat()
3696
+ reg = self._get_registry()
3697
+ rows = reg.query(
3698
+ "MATCH (i:Invitation) "
3699
+ "WHERE i.expires_at < $now AND i.accepted_at IS NULL "
3700
+ "AND (i.status IS NULL OR i.status <> 'expired') "
3701
+ "SET i.status = 'expired' "
3702
+ "RETURN count(i)",
3703
+ params={"now": now},
3704
+ ).result_set
3705
+ count = rows[0][0] if rows else 0
3706
+ return {"cleaned": count}
3707
+
3708
+ # ── Helpers ───────────────────────────────────────────────────
3709
+
3710
+ def _expand_kind(self, kind: str) -> list[str]:
3711
+ """Expand kind via subclassOf + equivalentTo for Cypher IN clause.
3712
+
3713
+ Uses PackRegistry.expand_kind(). Registry is loaded once and cached.
3714
+ Returns [kind] if no packs loaded or kind is unknown.
3715
+ """
3716
+ return _get_kind_expander().expand_kind(kind)
3717
+
3718
+ def _resolve_traversal_path(self, path: str) -> dict | None:
3719
+ """Resolve 'Product→Feature' to {predicate, fromKind, toKind} from pack registry.
3720
+
3721
+ Matches against pack-declared relations — fromKind/toKind suffixes
3722
+ (e.g., 'product-strategy:product' matches 'Product' via kind name 'product').
3723
+ Returns None if no matching relation found.
3724
+ """
3725
+ segments = [s.strip() for s in path.split("→")]
3726
+ if len(segments) < 2:
3727
+ # Hint: user may have used ASCII '->' instead of Unicode '→'
3728
+ if "->" in path:
3729
+ _logger.warning(
3730
+ "traversal_path uses ASCII '->' — use Unicode '→' instead "
3731
+ "(e.g., 'Product→Feature')"
3732
+ )
3733
+ return None
3734
+
3735
+ registry = _get_kind_expander()
3736
+ relations = registry.list_relations()
3737
+ if not relations:
3738
+ return None
3739
+
3740
+ from_name, to_name = segments[0].strip(), segments[1].strip()
3741
+
3742
+ for rel in relations:
3743
+ if "fromKind" not in rel or "toKind" not in rel:
3744
+ continue
3745
+ fk = rel["fromKind"]
3746
+ tk = rel["toKind"]
3747
+ # Extract kind name after the namespace prefix
3748
+ fk_name = fk.split(":", 1)[-1] if ":" in fk else fk
3749
+ tk_name = tk.split(":", 1)[-1] if ":" in tk else tk
3750
+ # Match case-insensitively against path segments
3751
+ if fk_name.lower() == from_name.lower() and tk_name.lower() == to_name.lower():
3752
+ return {"predicate": rel["predicate"], "fromKind": fk, "toKind": tk}
3753
+
3754
+ return None
3755
+
3756
+ @staticmethod
3757
+ def _validate_kind(kind: str) -> None:
3758
+ # ponytail: open-ended kind vocabularies — any string accepted.
3759
+ # Warning for unrecognized values; domain_loader.register_kind() can suppress.
3760
+ if kind not in known_kinds():
3761
+ _logger.warning(
3762
+ "Unrecognized pointKind %r. Known values: %s. "
3763
+ "Use tortoise.domain_loader.register_kind(%r) to register it.",
3764
+ kind, sorted(known_kinds()), kind,
3765
+ )
3766
+
3767
+
3768
+ # ── Entity CRUD (ONTOLOGY v2.5 §3, all 7 types) ──────────────────
3769
+
3770
+ def _create_entity(self, label: str, id_val: str, props: dict, event_type: str) -> dict:
3771
+ """Generic entity creation. Applies to graph via projection (event log + FalkorDB)."""
3772
+ # #329: id + sourcePath/source_path are server-managed — reject
3773
+ props = _sanitize_props(props, reject_id=True)
3774
+ proj = self._get_proj()
3775
+ # Build event dict
3776
+ event = {"type": event_type, "id": id_val, **props}
3777
+ # Normalize field names for projection compatibility
3778
+ if label == "Subject" and "subjectKind" in props:
3779
+ event["subject_kind"] = props["subjectKind"]
3780
+ if label == "Object" and "objectKind" in props:
3781
+ event["object_kind"] = props["objectKind"]
3782
+ if label == "Document" and "documentKind" in props:
3783
+ event["document_kind"] = props["documentKind"]
3784
+ if label == "Event" and "eventKind" in props:
3785
+ event["eventKind"] = event.get("eventKind", props.get("eventKind"))
3786
+ if "eventId" not in event:
3787
+ event["eventId"] = id_val
3788
+ if label == "Source":
3789
+ event["url"] = id_val
3790
+ # Apply through projection (writes to JSONL + FalkorDB)
3791
+ proj.apply(event)
3792
+ # #452: Subject/Object MERGE by name (content-hash dedup).
3793
+ # When the name already exists, the fresh id_val never lands on the
3794
+ # node (ON CREATE never fires). Re-fetch the canonical id from the
3795
+ # graph so callers get a usable return value — matching create_point
3796
+ # dedup behavior which returns the existing point id.
3797
+ canonical_id = id_val
3798
+ if label in ("Subject", "Object") and "name" in event:
3799
+ name = event["name"]
3800
+ r = proj.g.query(
3801
+ f"MATCH (n:{label} {{name: $name}}) RETURN n.id",
3802
+ params={"name": name},
3803
+ )
3804
+ if r.result_set and r.result_set[0]:
3805
+ canonical_id = r.result_set[0][0]
3806
+ # Wire edges after entity exists in graph (use canonical id)
3807
+ if props.get("authoredBy"):
3808
+ proj.create_authored_by(canonical_id, props["authoredBy"])
3809
+ if props.get("ownedBy"):
3810
+ proj.create_owned_by(canonical_id, props["ownedBy"])
3811
+ if props.get("managedBy"):
3812
+ proj.create_managed_by(canonical_id, props["managedBy"])
3813
+ return self._get_entity(canonical_id)
3814
+
3815
+ def _get_entity(self, id_val: str) -> dict:
3816
+ # NOTE (issue #327): Session/APIKey/Team/Tag nodes are intentionally
3817
+ # excluded from entity resolution — only Point/Subject/Object/Document/
3818
+ # Event/Source resolve (index-backed union). On a cross-label id
3819
+ # collision the first _RESOLVE_BRANCHES match wins (Point priority) —
3820
+ # more deterministic than the previous scan-order-arbitrary LIMIT 1.
3821
+ resolved = self._get_proj()._resolve_entity(
3822
+ id_val, by_id=True, by_eventId=True, by_url=True)
3823
+ return resolved[0]["properties"] if resolved else {}
3824
+
3825
+ def _update_entity(self, id_val: str, **props) -> dict:
3826
+ # #329: id + sourcePath/source_path are server-managed — reject
3827
+ props = _sanitize_props(props, reject_id=True)
3828
+ proj = self._get_proj()
3829
+ # NOTE (issue #327): like _get_entity, entity mutation covers only the
3830
+ # canonical labels (Point/Subject/Object/Document/Source/Event).
3831
+ # Session/APIKey/Team/Tag nodes are intentionally NOT updated — legacy
3832
+ # matched them via id/eventId but no caller relies on it.
3833
+ # Per-label indexed writes (id OR eventId — original predicate; no url).
3834
+ # UNION cannot carry SET, so run each branch sequentially (#327).
3835
+ for label, prop in (("Point", "id"), ("Subject", "id"), ("Object", "id"),
3836
+ ("Document", "id"), ("Source", "id"), ("Event", "eventId")):
3837
+ proj.g.query(
3838
+ f"MATCH (n:{label} {{{prop}:$id}}) SET n += $p",
3839
+ params={"id": id_val, "p": props},
3840
+ )
3841
+ return self._get_entity(id_val)
3842
+
3843
+ def _delete_entity(self, id_val: str) -> bool:
3844
+ proj = self._get_proj()
3845
+ # NOTE (issue #327): deletion covers only canonical entity labels —
3846
+ # Session/APIKey/Team/Tag nodes are intentionally NOT deleted (legacy
3847
+ # matched them by id/eventId; no caller relies on it).
3848
+ total = 0
3849
+ for label, prop in (("Point", "id"), ("Subject", "id"), ("Object", "id"),
3850
+ ("Document", "id"), ("Source", "id"), ("Event", "eventId")):
3851
+ r = proj.g.query(
3852
+ f"MATCH (n:{label} {{{prop}:$id}}) DETACH DELETE n RETURN count(n)",
3853
+ params={"id": id_val},
3854
+ )
3855
+ if r.result_set:
3856
+ total += r.result_set[0][0]
3857
+ return bool(total)
3858
+
3859
+ def create_subject(self, name: str, subjectKind: str = "other", **props) -> dict:
3860
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
3861
+ return self._create_entity("Subject", self.ulid(), {"name": name, "subjectKind": subjectKind, "status": "live", **props}, "SubjectAdded")
3862
+
3863
+ def create_object(self, name: str, objectKind: str = "other", **props) -> dict:
3864
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
3865
+ return self._create_entity("Object", self.ulid(), {"name": name, "objectKind": objectKind, "status": "live", **props}, "ObjectRegistered")
3866
+
3867
+ def create_event(self, name: str, eventKind: str, **props) -> dict:
3868
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
3869
+ """Create an Event node.
3870
+
3871
+ If aboutSubject, aboutObject, aboutPoint, or aboutDocument are provided
3872
+ in **props, they are extracted and wired as graph edges:
3873
+ (Event)-[:aboutSubject]->(Subject)
3874
+ (Event)-[:aboutObject]->(Object)
3875
+ (Event)-[:aboutPoint]->(Point)
3876
+ (Event)-[:aboutDocument]->(Document)
3877
+ rather than stored as string properties.
3878
+ """
3879
+ eid = self.ulid()
3880
+ about_subject = props.pop("aboutSubject", None)
3881
+ about_object = props.pop("aboutObject", None)
3882
+ about_point = props.pop("aboutPoint", None)
3883
+ about_document = props.pop("aboutDocument", None)
3884
+ result = self._create_entity("Event", eid, {"eventId": eid, "name": name, "eventKind": eventKind, "eventStatus": "scheduled", **props}, "EventRecorded")
3885
+ proj = self._get_proj()
3886
+ if about_subject:
3887
+ proj.create_about_edge(eid, about_subject, "aboutSubject")
3888
+ # Only name-resolve if it looks like a plain name, not an ID
3889
+ if isinstance(about_subject, str) and not _is_ulid(about_subject):
3890
+ proj._create_about_edges(eid, about_subject)
3891
+ if about_object:
3892
+ proj.create_about_edge(eid, about_object, "aboutObject")
3893
+ if isinstance(about_object, str) and not _is_ulid(about_object):
3894
+ proj._create_about_edges(eid, about_object)
3895
+ if about_point:
3896
+ proj.create_about_edge(eid, about_point, "aboutPoint")
3897
+ if isinstance(about_point, str) and not _is_ulid(about_point):
3898
+ proj._create_about_edges(eid, about_point)
3899
+ if about_document:
3900
+ proj.create_about_edge(eid, about_document, "aboutDocument")
3901
+ if isinstance(about_document, str) and not _is_ulid(about_document):
3902
+ proj._create_about_edges(eid, about_document)
3903
+ return result
3904
+
3905
+
3906
+ # ── Session Indexing (AgentSession) ─────────────────────────
3907
+
3908
+ def _session_embedding(self, name: str, summary: str = "",
3909
+ keywords: list[str] | None = None,
3910
+ topics: list[str] | None = None) -> list[float] | None:
3911
+ """Compute the embedding for an AgentSession Event (#244).
3912
+
3913
+ name + summary + keywords + topics → 384-dim vector, or None when the
3914
+ model is unavailable (session indexing must never depend on it).
3915
+ """
3916
+ from .session_indexer import compute_session_embedding
3917
+ return compute_session_embedding(name, summary, keywords, topics)
3918
+
3919
+ def search_sessions(self, query: str, *, agent: str | None = None,
3920
+ topics: list[str] | None = None,
3921
+ after: "datetime | str | None" = None,
3922
+ before: "datetime | str | None" = None,
3923
+ limit: int = 10, offset: int = 0) -> list[dict]:
3924
+ """Search indexed agent sessions. Returns Events with metadata snippets.
3925
+
3926
+ Routes through the hybrid engine (tortoise_fts_query entity_type='event'
3927
+ kind='AgentSession'): RRF fusion of FTS (Event subject+name index),
3928
+ vector (session embeddings computed at index time, #244) and structural
3929
+ (eventKind) strategies. Results are ordered by relevance with startedAt
3930
+ DESC as tiebreak.
3931
+
3932
+ agent/topics post-filter the candidates. after/before bound the search
3933
+ to sessions whose ``startedAt`` falls in ``[after, before]`` (inclusive).
3934
+ Each may be a ``datetime`` or an ISO-8601 string (``Z`` or offset
3935
+ accepted); both are normalized to UTC ISO-8601 so the comparison
3936
+ against stored ``startedAt`` values is valid regardless of the caller's
3937
+ timezone. Sessions that lack a ``startedAt`` are EXCLUDED whenever a
3938
+ bound is set.
3939
+
3940
+ When no semantic strategy contributed (FTS/vector unavailable — e.g.
3941
+ embedded FalkorDBLite without embeddings, prod before #160 deploys),
3942
+ falls back to the legacy keyword CONTAINS surface (name + keywords) so
3943
+ the previous behavior keeps working.
3944
+ """
3945
+ if not query or not query.strip():
3946
+ return []
3947
+ proj = self._get_proj()
3948
+ has_bound = after is not None or before is not None
3949
+ after_utc = _to_iso_utc(after) if after is not None else None
3950
+ before_utc = _to_iso_utc(before) if before is not None else None
3951
+
3952
+ # ── Hybrid route: RRF fusion of FTS + vector + structural ──
3953
+ # Generous candidate pool — agent/topics/temporal filters drop rows
3954
+ # post-retrieval, so fetch beyond the caller's limit + offset.
3955
+ candidate_limit = max(limit * 5, 50) + offset
3956
+ hybrid = self.tortoise_fts_query(
3957
+ query, kind="AgentSession", entity_type="event",
3958
+ limit=candidate_limit,
3959
+ )
3960
+ has_semantic = any(
3961
+ r.get("scores")
3962
+ and (r["scores"].get("fts") is not None
3963
+ or r["scores"].get("vector") is not None)
3964
+ for r in hybrid
3965
+ )
3966
+ if has_semantic and hybrid:
3967
+ # Precision gate (#244 review): rows with NO semantic signal — no
3968
+ # FTS score and no vector score (structural-only; the kind filter
3969
+ # matches ALL AgentSession events with score 1.0) are NOT results,
3970
+ # they only fed the RRF candidate pool. Note: vector-only rows are
3971
+ # deliberately kept — word-distinct semantic recall is the point
3972
+ # of #244 ("port migration" finds a session about changing the
3973
+ # FalkorDB default port); see docstring. The brute-force vector
3974
+ # strategy is threshold-less, so those rows are ranked nearest-
3975
+ # neighbors-first and precision drops when a query has no real
3976
+ # semantic match (documented behavior).
3977
+ ids = [r["id"] for r in hybrid]
3978
+ rows = proj.g.query(
3979
+ "MATCH (e:Event) WHERE e.eventId IN $ids RETURN properties(e)",
3980
+ params={"ids": ids},
3981
+ ).result_set
3982
+ props_by_id = {}
3983
+ for row in rows:
3984
+ props = dict(row[0])
3985
+ if props.get("eventId"):
3986
+ props_by_id[props["eventId"]] = props
3987
+ ranked = []
3988
+ for r in hybrid:
3989
+ props = props_by_id.get(r["id"])
3990
+ if props is None:
3991
+ continue
3992
+ if agent and props.get("agent") != agent:
3993
+ continue
3994
+ if topics:
3995
+ s_topics = set(props.get("topics") or [])
3996
+ if not any(t in s_topics for t in topics):
3997
+ continue
3998
+ if has_bound:
3999
+ started = props.get("startedAt")
4000
+ if not started:
4001
+ continue # sessions without startedAt excluded when a bound is set
4002
+ if after_utc is not None and started < after_utc:
4003
+ continue
4004
+ if before_utc is not None and started > before_utc:
4005
+ continue
4006
+ # Precision gate (#244 review): structural-only rows (no FTS,
4007
+ # no vector score) are NOT results — a session that neither
4008
+ # keyword-matches nor semantically matches must not appear.
4009
+ scores = r.get("scores") or {}
4010
+ if scores.get("fts") is None and scores.get("vector") is None:
4011
+ continue
4012
+ ranked.append((scores.get("rrf") or 0.0, props))
4013
+ # Relevance (RRF) desc, startedAt DESC as tiebreak (missing = last)
4014
+ ranked.sort(
4015
+ key=lambda item: (item[0], item[1].get("startedAt") or ""),
4016
+ reverse=True,
4017
+ )
4018
+ return [props for _, props in ranked[offset:offset + limit]]
4019
+
4020
+ # ── Legacy keyword fallback (no FTS/vector contribution) ──
4021
+ # Preserves the pre-#244 CONTAINS surface (name + keywords) plus the
4022
+ # #243 temporal filters (after/before, ISO-8601 UTC normalization,
4023
+ # startedAt IS NOT NULL exclusion when a bound is set).
4024
+ clauses = ["e.eventKind = 'AgentSession'"]
4025
+ params: dict = {"limit": max(limit * 3, 30)}
4026
+ query_lower = query.strip().lower()
4027
+ clauses.append("(toLower(e.name) CONTAINS $q OR any(kw IN e.keywords WHERE toLower(kw) CONTAINS $q))")
4028
+ params["q"] = query_lower
4029
+ if agent:
4030
+ clauses.append("e.agent = $agent")
4031
+ params["agent"] = agent
4032
+ if topics:
4033
+ topic_clauses = []
4034
+ for i, t in enumerate(topics):
4035
+ pk = f"topic{i}"
4036
+ topic_clauses.append(f"${pk} IN e.topics")
4037
+ params[pk] = t
4038
+ clauses.append(f"({' OR '.join(topic_clauses)})")
4039
+ has_bound = after is not None or before is not None
4040
+ if has_bound:
4041
+ # Explicitly drop sessions without startedAt — same outcome as
4042
+ # null-comparison semantics, but self-documenting and robust.
4043
+ clauses.append("e.startedAt IS NOT NULL")
4044
+ if after is not None:
4045
+ clauses.append("e.startedAt >= $after")
4046
+ params["after"] = _to_iso_utc(after)
4047
+ if before is not None:
4048
+ clauses.append("e.startedAt <= $before")
4049
+ params["before"] = _to_iso_utc(before)
4050
+ where = " AND ".join(clauses)
4051
+ params["offset"] = offset
4052
+ rows = proj.g.query(
4053
+ f"MATCH (e:Event) WHERE {where} "
4054
+ "RETURN properties(e) ORDER BY e.startedAt DESC SKIP $offset LIMIT $limit",
4055
+ params=params,
4056
+ ).result_set
4057
+ # Fetch a bit extra for scoring headroom, but honor the caller's limit.
4058
+ return [dict(r[0]) for r in rows[:limit]]
4059
+
4060
+ def get_events(self, eventKind: str | None = None, limit: int = 20) -> list[dict]:
4061
+ """Get recent Events, optionally filtered by eventKind."""
4062
+ proj = self._get_proj()
4063
+ if eventKind:
4064
+ return [r[0] for r in proj.g.query(
4065
+ "MATCH (e:Event {eventKind: $ek}) RETURN properties(e) ORDER BY e.startedAt DESC LIMIT $lim",
4066
+ params={"ek": eventKind, "lim": limit}
4067
+ ).result_set]
4068
+ return [r[0] for r in proj.g.query(
4069
+ "MATCH (e:Event) RETURN properties(e) ORDER BY e.startedAt DESC LIMIT $lim",
4070
+ params={"lim": limit}
4071
+ ).result_set]
4072
+
4073
+ def get_session(self, session_id: str) -> dict | None:
4074
+ """Get a single session Event by session_id (matches snake or camel case)."""
4075
+ if not session_id:
4076
+ return None
4077
+ proj = self._get_proj()
4078
+ rows = proj.g.query(
4079
+ "MATCH (e:Event {eventKind: 'AgentSession'}) "
4080
+ "WHERE e.session_id = $sid OR e.sessionId = $sid RETURN properties(e)",
4081
+ params={"sid": session_id}
4082
+ ).result_set
4083
+ return rows[0][0] if rows else None
4084
+
4085
+ def index_sessions(self, directory: str, extract_metadata: bool = True,
4086
+ llm_model: str | None = "gpt-5-mini",
4087
+ progress_file: str | None = None) -> dict:
4088
+ """Index session files as AgentSession Events.
4089
+ Thin wrapper around ingest_corpus with AgentSession defaults."""
4090
+ return self.ingest_corpus(directory, eventKind="AgentSession",
4091
+ extract_metadata=extract_metadata,
4092
+ llm_model=llm_model,
4093
+ progress_file=progress_file)
4094
+
4095
+ def _connect_issue_objects(self, event_id: str, metadata: dict) -> int:
4096
+ """Create INSTANTIATES edges from an AgentSession Event to issue/PR Objects."""
4097
+ proj = self._get_proj()
4098
+ connected = 0
4099
+ for key in ("issues", "prs"):
4100
+ for item in metadata.get(key, []) or []:
4101
+ if isinstance(item, dict):
4102
+ oid = item.get("id") or item.get("number")
4103
+ name = item.get("title") or item.get("name") or str(item)
4104
+ else:
4105
+ oid = None
4106
+ name = str(item)
4107
+ if not oid:
4108
+ # Deterministic hash (builtin hash() is salted per-process →
4109
+ # would create duplicate Objects on every run).
4110
+ oid = f"{key.rstrip('s')}_{hashlib.sha256(name.encode()).hexdigest()[:8]}"
4111
+ okind = "pr" if key == "prs" else "issue"
4112
+ proj.g.query(
4113
+ "MERGE (o:Object {id:$oid}) SET o.name=$name, o.objectKind=$okind "
4114
+ "WITH o MATCH (e:Event {eventId:$eid}) MERGE (e)-[:INSTANTIATES]->(o)",
4115
+ params={"oid": oid, "name": name[:200], "eid": event_id, "okind": okind},
4116
+ )
4117
+ connected += 1
4118
+ return connected
4119
+
4120
+
4121
+ def create_document(self, title: str, documentKind: str, **props) -> dict:
4122
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
4123
+ did = self.ulid()
4124
+ return self._create_entity("Document", did, {"title": title, "documentKind": documentKind, "objectKind": "document", "status": "draft", **props}, "DocumentCreated")
4125
+
4126
+ def create_source(self, url: str, sourceKind: str, *,
4127
+ tier: str | None = None, sourceDate: str | None = None,
4128
+ **props) -> dict:
4129
+ """Create (or merge) a Source node (issue #398 Task 6).
4130
+
4131
+ Dual-write rule (ontology v3.1 §4.6 + code reader contract):
4132
+ - ``tier`` given → stored on ``credibilityTier`` (the property the
4133
+ inheritance adapter reads); ``sourceKind`` left untouched.
4134
+ - ``sourceKind`` is itself a tier-form (T0-T4) → mirrored to
4135
+ ``credibilityTier`` as well (canonical per ontology).
4136
+ - An EXISTING Source (URL collision) NEVER has its ``sourceKind``
4137
+ overwritten — tier lands on ``credibilityTier`` only.
4138
+ ``sourceDate`` is the evidence-age clock for decay (falls back to
4139
+ ``ingestedAt`` — the documented pipeline-arrival proxy). Invalid tier
4140
+ values raise ValueError.
4141
+ """
4142
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
4143
+ if not url or not url.strip():
4144
+ raise ValueError("url must be a non-empty string")
4145
+ from tortoise.source_credibility import TIER_PRIORS, canonical_tier
4146
+ if tier is not None:
4147
+ _orig_tier = tier
4148
+ tier = canonical_tier(tier)
4149
+ if tier is None:
4150
+ raise ValueError(
4151
+ f"Invalid tier {_orig_tier!r} — must be T0..T4 or a legacy alias "
4152
+ f"(gold/high/medium/low/unverified)"
4153
+ )
4154
+ if sourceKind in TIER_PRIORS and tier is None:
4155
+ tier = sourceKind # tier-form sourceKind mirrors to credibilityTier
4156
+ ev = {
4157
+ "url": url,
4158
+ "sourceKind": sourceKind,
4159
+ "ingestedAt": __import__('datetime').datetime.now(
4160
+ __import__('datetime').timezone.utc).isoformat(),
4161
+ **props,
4162
+ }
4163
+ if tier is not None:
4164
+ ev["credibilityTier"] = tier
4165
+ if sourceDate is not None:
4166
+ ev["sourceDate"] = sourceDate
4167
+ result = self._create_entity("Source", url, ev, "SourceCreated")
4168
+ # Write events invalidate the inheritance gate + reliability cache
4169
+ self._invalidate_inheritance_gate_for_source(url)
4170
+ self._clear_reliability_cache(url)
4171
+ return result
4172
+
4173
+ def set_source_tier(self, url: str, tier: str) -> dict:
4174
+ """Set (or change) a Source's credibility tier — non-destructive.
4175
+
4176
+ Writes ``credibilityTier`` only; never touches ``sourceKind`` (legacy
4177
+ type strings are preserved). Mirrors to ``sourceKind`` when it is
4178
+ already a tier-form (keeps the dual-write invariant). Dirty-marks the
4179
+ inheritance gate + clears the reliability cache.
4180
+ """
4181
+ from tortoise.source_credibility import TIER_PRIORS, canonical_tier
4182
+ _orig = tier
4183
+ tier = canonical_tier(tier)
4184
+ if tier is None:
4185
+ raise ValueError(
4186
+ f"Invalid tier {_orig!r} — must be T0..T4 or a legacy alias "
4187
+ f"(gold/high/medium/low/unverified)"
4188
+ )
4189
+ proj = self._get_proj()
4190
+ rows = proj.g.query(
4191
+ "MATCH (s:Source {url:$url}) RETURN s.sourceKind",
4192
+ params={"url": url},
4193
+ ).result_set
4194
+ if not rows:
4195
+ raise ValueError(f"Source {url} does not exist")
4196
+ skind = rows[0][0]
4197
+ if skind in TIER_PRIORS:
4198
+ # Keep the dual-write invariant: tier-form sourceKind mirrors the tier
4199
+ proj.g.query(
4200
+ "MATCH (s:Source {url:$url}) SET s.credibilityTier = $t, s.sourceKind = $t",
4201
+ params={"url": url, "t": tier},
4202
+ )
4203
+ else:
4204
+ proj.g.query(
4205
+ "MATCH (s:Source {url:$url}) SET s.credibilityTier = $t",
4206
+ params={"url": url, "t": tier},
4207
+ )
4208
+ self._invalidate_inheritance_gate_for_source(url)
4209
+ self._clear_reliability_cache(url)
4210
+ return {"url": url, "credibilityTier": tier, "sourceKind": skind}
4211
+
4212
+ # ── Entity Derivation (#122 Part 2) ──────────────────────────
4213
+
4214
+ def create_derivation(self, src_id: str, dst_id: str) -> dict:
4215
+ """Create a wasDerivedFrom edge: (dst)-[:wasDerivedFrom]->(src).
4216
+
4217
+ PROV-O entity derivation — dst was derived from src. Distinct from
4218
+ extractedFrom (claim provenance) — wasDerivedFrom is Object→Object
4219
+ entity derivation.
4220
+ """
4221
+ proj = self._get_proj()
4222
+ ok = proj.create_edge(dst_id, src_id, "wasDerivedFrom")
4223
+ return {"derived": ok, "src": src_id, "dst": dst_id}
4224
+
4225
+ # ── Source reliability (issue #398 Task 4) ──────────────────────
4226
+
4227
+ def _compute_source_prior(self, url: str) -> dict | None:
4228
+ """Compute a Source's effective Beta prior + components (single source of truth).
4229
+
4230
+ Used by BOTH the inheritance adapter (per-point base weight) and the
4231
+ reliability cache — the two cannot drift. Returns None when the source
4232
+ is untiered (no inheritance contribution). Assessment factor is read
4233
+ from `pointKind='assessment'` Points (latest per assessor wins by
4234
+ createdAt; outdated filtered); until Task 5 lands, factor = 1.0.
4235
+ """
4236
+ import os
4237
+ from datetime import datetime, timezone
4238
+ from tortoise.source_credibility import (
4239
+ aggregate_prior,
4240
+ assessment_factor,
4241
+ resolve_tier,
4242
+ )
4243
+ proj = self._get_proj()
4244
+ rows = proj.g.query(
4245
+ "MATCH (s:Source {url:$url}) "
4246
+ "RETURN s.credibilityTier, s.sourceKind, s.sourceDate, s.ingestedAt",
4247
+ params={"url": url},
4248
+ ).result_set
4249
+ if not rows:
4250
+ return None
4251
+ ctier, skind, sdate, ingested = rows[0]
4252
+ tier = resolve_tier(ctier, skind)
4253
+ if tier is None:
4254
+ return None
4255
+
4256
+ # Batched assessment aggregation (latest per (targetSource, assessor),
4257
+ # outdated filtered; assessorReputation snapshotted at write time).
4258
+ arows = proj.g.query(
4259
+ "MATCH (p:Point {pointKind:'assessment'}) "
4260
+ "WHERE p.targetSource = $url AND (p.outdated IS NULL OR p.outdated = false) "
4261
+ "RETURN p.assessor, p.score, coalesce(p.assessorReputation, 0.5), p.createdAt "
4262
+ "ORDER BY p.createdAt",
4263
+ params={"url": url},
4264
+ ).result_set
4265
+ latest: dict[str, tuple[float, float]] = {}
4266
+ for assessor, score, rep, _created in arows:
4267
+ try:
4268
+ latest[assessor] = (float(rep), float(score))
4269
+ except (TypeError, ValueError):
4270
+ continue
4271
+ assessments = list(latest.values())
4272
+ factor = assessment_factor(assessments)
4273
+
4274
+ from tortoise.source_credibility import decay_factor as _decay_factor
4275
+ alpha, beta = aggregate_prior(
4276
+ [(tier, sdate, ingested, factor)],
4277
+ recency_decay=float(os.environ.get("TORTOISE_EP_RECENCY_DECAY", "0.95")),
4278
+ )
4279
+ return {
4280
+ "tier": tier,
4281
+ "sourceDate": sdate,
4282
+ "ingestedAt": ingested,
4283
+ "decay": _decay_factor(
4284
+ sdate, ingested,
4285
+ recency_decay=float(os.environ.get("TORTOISE_EP_RECENCY_DECAY", "0.95")),
4286
+ tier=tier,
4287
+ ),
4288
+ "factor": factor,
4289
+ "assessment_count": len(assessments),
4290
+ "alpha": alpha,
4291
+ "beta": beta,
4292
+ }
4293
+
4294
+ def get_source_reliability(self, url: str) -> dict:
4295
+ """Derive a Source's reliability (0-1) — query-time, cache-consistency-checked.
4296
+
4297
+ Returns {"url", "reliability" (float 0-1 or None), "components",
4298
+ "cache": "fresh"|"recomputed"|"miss"}. The reliability value is the mean
4299
+ of the SAME modulated prior EP uses as base weight (single source of
4300
+ truth ``_compute_source_prior``), so ``reliability == inherited prior
4301
+ mean`` for single-source points (consistency invariant). Untiered +
4302
+ unassessed → None (reason 'untiered'). The cache
4303
+ (reliability/reliabilityComponents/reliability_derived_at) is a
4304
+ documented projection — recomputed when stale (interval elapsed or tier/
4305
+ sourceDate changed vs cached components) or after write events
4306
+ (set_source_tier/assess_source/create_source(tier=)).
4307
+ """
4308
+ import os
4309
+ from datetime import datetime, timezone
4310
+ from tortoise.source_credibility import resolve_tier
4311
+ proj = self._get_proj()
4312
+ now = datetime.now(timezone.utc)
4313
+ interval = float(os.environ.get("TORTOISE_EP_REINHERIT_INTERVAL", "3600"))
4314
+
4315
+ # Cache freshness check
4316
+ rows = proj.g.query(
4317
+ "MATCH (s:Source {url:$url}) "
4318
+ "RETURN s.reliability, s.reliabilityComponents, s.reliability_derived_at, "
4319
+ "s.credibilityTier, s.sourceKind, s.sourceDate, s.ingestedAt",
4320
+ params={"url": url},
4321
+ ).result_set
4322
+ cached = None
4323
+ if rows and rows[0][2]:
4324
+ cached_rel, cached_comp_raw, cached_at, c_tier, c_kind, c_sdate, c_ingested = rows[0]
4325
+ fresh = False
4326
+ try:
4327
+ derived = datetime.fromisoformat(str(cached_at).replace("Z", "+00:00"))
4328
+ if derived.tzinfo is None:
4329
+ derived = derived.replace(tzinfo=timezone.utc)
4330
+ fresh = (now - derived).total_seconds() < interval
4331
+ except (ValueError, TypeError):
4332
+ fresh = False
4333
+ if fresh:
4334
+ try:
4335
+ import json as _json
4336
+ cached_comp = _json.loads(cached_comp_raw) if cached_comp_raw else {}
4337
+ # Inputs unchanged → serve cache (tier, sourceDate, ingestedAt
4338
+ # are the derivation inputs; assessments clear the cache at write)
4339
+ if (cached_comp.get("tier") == resolve_tier(c_tier, c_kind)
4340
+ and cached_comp.get("sourceDate") == c_sdate
4341
+ and cached_comp.get("ingestedAt") == rows[0][5]):
4342
+ cached = (cached_rel, cached_comp)
4343
+ except (TypeError, ValueError, KeyError):
4344
+ cached = None
4345
+
4346
+ if cached is not None:
4347
+ rel, comp = cached
4348
+ return {"url": url, "reliability": rel, "components": comp, "cache": "fresh"}
4349
+
4350
+ # Recompute from the single source of truth
4351
+ prior = self._compute_source_prior(url)
4352
+ if prior is None:
4353
+ # Untiered: assessment-only reliability (display — never feeds EP)
4354
+ arows = proj.g.query(
4355
+ "MATCH (p:Point {pointKind:'assessment'}) "
4356
+ "WHERE p.targetSource = $url AND (p.outdated IS NULL OR p.outdated = false) "
4357
+ "RETURN p.assessor, p.score, coalesce(p.assessorReputation, 0.5), p.createdAt "
4358
+ "ORDER BY p.createdAt",
4359
+ params={"url": url},
4360
+ ).result_set
4361
+ if arows:
4362
+ # Latest per (url, assessor) — mirrors _compute_source_prior dedup
4363
+ latest: dict[str, tuple[float, float]] = {}
4364
+ for assessor, score, rep, _created in arows:
4365
+ try:
4366
+ latest[assessor] = (float(rep), float(score))
4367
+ except (TypeError, ValueError):
4368
+ continue
4369
+ reps = [r for r, _s in latest.values()]
4370
+ rep_sum = sum(reps)
4371
+ weighted = (sum(r * s for r, s in latest.values()) / rep_sum
4372
+ if rep_sum else 0.0)
4373
+ if weighted != weighted: # NaN guard
4374
+ weighted = 0.0
4375
+ comp = {"tier": None, "reason": "untiered; assessment-only",
4376
+ "assessment_count": len(arows),
4377
+ "assessment_weighted_mean": weighted}
4378
+ self._write_reliability_cache(url, weighted, comp, now)
4379
+ return {"url": url, "reliability": weighted, "components": comp,
4380
+ "cache": "recomputed"}
4381
+ comp = {"tier": None, "reason": "untiered", "assessment_count": 0}
4382
+ self._write_reliability_cache(url, None, comp, now)
4383
+ return {"url": url, "reliability": None, "components": comp, "cache": "miss"}
4384
+
4385
+ mean = prior["alpha"] / (prior["alpha"] + prior["beta"])
4386
+ comp = {
4387
+ "tier": prior["tier"],
4388
+ "sourceDate": prior["sourceDate"],
4389
+ "ingestedAt": prior["ingestedAt"],
4390
+ "factor": prior["factor"],
4391
+ "assessment_count": prior["assessment_count"],
4392
+ "decay": prior["decay"],
4393
+ "mean": mean,
4394
+ }
4395
+ self._write_reliability_cache(url, mean, comp, now)
4396
+ return {"url": url, "reliability": mean, "components": comp, "cache": "recomputed"}
4397
+
4398
+ def assess_source(self, url: str, assessor: str, score: float, rationale: str) -> dict:
4399
+ """Record an agent's assessment of a Source (issue #398 Task 5).
4400
+
4401
+ Creates a ``pointKind='assessment'`` Statement Point (ontology §2 —
4402
+ evaluations of subjects are Points with EP confidence, NOT edges),
4403
+ property-linked via ``targetSource`` (never ``extractedFrom`` — it is
4404
+ evidence ABOUT the source, not extracted FROM it).
4405
+
4406
+ Semantics:
4407
+ - score ∈ [0, 1] (non-numeric → ValueError); rationale required.
4408
+ - Assessor reputation is SNAPSHOTTED at write time
4409
+ (``compute_reputation(assessor).mean``, stored as
4410
+ ``assessorReputation``) so later reputation changes never rewrite
4411
+ past assessments' factors.
4412
+ - Latest-wins per (url, assessor): older assessments from the same
4413
+ assessor are marked ``outdated:true`` — the aggregation query picks
4414
+ the latest active assessment by construction (crash-safe).
4415
+ - The assessment factor is clamped [0.1, 2.0] at the read path.
4416
+ - Refreshes the reliability cache + dirty-marks the inheritance gate
4417
+ so EP recomputes promptly.
4418
+ """
4419
+ try:
4420
+ score_f = float(score)
4421
+ except (TypeError, ValueError):
4422
+ raise ValueError(f"score must be numeric, got {score!r}") from None
4423
+ if not (0.0 <= score_f <= 1.0):
4424
+ raise ValueError(f"score must be in [0, 1], got {score_f}")
4425
+ if not rationale or not str(rationale).strip():
4426
+ raise ValueError("rationale is required")
4427
+ if not assessor or not str(assessor).strip():
4428
+ raise ValueError("assessor is required")
4429
+ if not url or not str(url).strip():
4430
+ raise ValueError("url is required")
4431
+
4432
+ from datetime import datetime, timezone
4433
+ rep = self.compute_reputation(str(assessor))["mean"]
4434
+ now = datetime.now(timezone.utc).isoformat()
4435
+
4436
+ proj = self._get_proj()
4437
+ # Create the new assessment FIRST, then mark older ones outdated EXCLUDING
4438
+ # the new point (crash-safe: a failure between the two leaves the new
4439
+ # point active and the old one active — the read path dedupes
4440
+ # latest-per-(url, assessor) by createdAt, so no double-count; a failure
4441
+ # before the mark leaves the previous assessment intact, not orphaned).
4442
+ p = self.create_point(
4443
+ "assessment", str(rationale).strip(),
4444
+ props={
4445
+ "targetSource": url,
4446
+ "assessor": str(assessor),
4447
+ "score": score_f,
4448
+ "assessorReputation": rep,
4449
+ "createdAt": now,
4450
+ },
4451
+ )
4452
+ proj.g.query(
4453
+ "MATCH (p:Point {pointKind:'assessment'}) "
4454
+ "WHERE p.targetSource = $url AND p.assessor = $assessor "
4455
+ " AND p.id <> $new_id "
4456
+ " AND (p.outdated IS NULL OR p.outdated = false) "
4457
+ "SET p.outdated = true",
4458
+ params={"url": url, "assessor": str(assessor), "new_id": p["id"]},
4459
+ )
4460
+ # Refresh reliability cache (clear → next read recomputes) + dirty-mark
4461
+ # the inheritance gate so EP recomputes promptly.
4462
+ self._invalidate_inheritance_gate_for_source(url)
4463
+ self._clear_reliability_cache(url)
4464
+ return {"assessment_point_id": p["id"], "url": url, "assessor": str(assessor),
4465
+ "score": score_f, "reputation": rep}
4466
+
4467
+ def _invalidate_inheritance_gate_for_source(self, url: str) -> None:
4468
+ """Dirty-mark all points extracted from a source (inheritance recompute)."""
4469
+ proj = self._get_proj()
4470
+ rows = proj.g.query(
4471
+ "MATCH (n:Point)-[:extractedFrom]->(s:Source {url:$url}) "
4472
+ "RETURN n.id",
4473
+ params={"url": url},
4474
+ ).result_set
4475
+ pids = [r[0] for r in rows]
4476
+ self._invalidate_inheritance_gate(pids)
4477
+
4478
+ def _write_reliability_cache(self, url: str, reliability, components: dict, now) -> None:
4479
+ """Write-through reliability projection on the Source node (documented cache)."""
4480
+ import json as _json
4481
+ proj = self._get_proj()
4482
+ proj.g.query(
4483
+ "MATCH (s:Source {url:$url}) "
4484
+ "SET s.reliability = $r, s.reliabilityComponents = $c, "
4485
+ "s.reliability_derived_at = $ts",
4486
+ params={"url": url, "r": reliability, "c": _json.dumps(components),
4487
+ "ts": now.isoformat()},
4488
+ )
4489
+
4490
+ def _clear_reliability_cache(self, url: str) -> None:
4491
+ """Invalidate the reliability cache (next read recomputes from scratch).
4492
+
4493
+ Called by write events that change the derivation inputs: assess_source,
4494
+ set_source_tier, create_source(tier=). Prevents indefinite staleness —
4495
+ the cache is a documented projection, never authoritative.
4496
+ """
4497
+ proj = self._get_proj()
4498
+ proj.g.query(
4499
+ "MATCH (s:Source {url:$url}) "
4500
+ "REMOVE s.reliability, s.reliabilityComponents, s.reliability_derived_at",
4501
+ params={"url": url},
4502
+ )
4503
+
4504
+ # ── Reputation (#122 Part 4) ─────────────────────────────────
4505
+
4506
+ def compute_reputation(self, subject_id: str) -> dict:
4507
+ """Derive reputation score for a Subject from event outcomes.
4508
+
4509
+ Traverses: Subject -[:performs]-> Event -[:IMPL|NAND]-> Point
4510
+ Aggregates success/failure from direct event outcomes.
4511
+ Returns derived score (NOT stored).
4512
+
4513
+ Returns {mean, total_events, impl_count, nand_count, alpha, beta, outcomes}.
4514
+ """
4515
+ proj = self._get_proj()
4516
+ # Try exact id match first, fall back to name if no id match (#152).
4517
+ # Prevents merging outcomes from Subject A (id='alice') with Subject B
4518
+ # (name='alice') when a subject_id collides with another Subject's name.
4519
+ id_check = proj.g.query(
4520
+ "MATCH (s:Subject {id: $sid}) RETURN count(s) > 0",
4521
+ params={"sid": subject_id},
4522
+ ).result_set
4523
+ if id_check and id_check[0][0]:
4524
+ match_clause = "s.id = $sid"
4525
+ else:
4526
+ match_clause = "s.name = $sid"
4527
+
4528
+ # Direct: Event connects directly to claim Points via IMPL/NAND
4529
+ # (Operators connect ONLY epistemic targets per ONTOLOGY: Event→Point, Point→Point)
4530
+ impl_rows = proj.g.query(
4531
+ "MATCH (s:Subject)-[:performs]->(e:Event) "
4532
+ "MATCH (e)-[:IMPL]->(p:Point) "
4533
+ "WHERE (p.is_operator IS NULL OR p.is_operator = false) "
4534
+ "AND (p.outdated IS NULL OR p.outdated = false) "
4535
+ "AND e.eventKind <> 'humanApproval' " # #531: no reputation from own approvals
4536
+ f"AND {match_clause} "
4537
+ "RETURN p.id, p.content, coalesce(p.confidence, 0.5) AS conf",
4538
+ params={"sid": subject_id},
4539
+ ).result_set
4540
+ nand_rows = proj.g.query(
4541
+ "MATCH (s:Subject)-[:performs]->(e:Event) "
4542
+ "MATCH (e)-[:NAND]->(p:Point) "
4543
+ "WHERE (p.is_operator IS NULL OR p.is_operator = false) "
4544
+ "AND (p.outdated IS NULL OR p.outdated = false) "
4545
+ "AND e.eventKind <> 'humanApproval' " # #531: no reputation from own approvals
4546
+ f"AND {match_clause} "
4547
+ "RETURN p.id, p.content, coalesce(p.confidence, 0.5) AS conf",
4548
+ params={"sid": subject_id},
4549
+ ).result_set
4550
+
4551
+ # Collect outcomes
4552
+ outcomes: list[dict] = []
4553
+ for row in impl_rows:
4554
+ outcomes.append({"point_id": row[0], "content": row[1], "confidence": float(row[2]), "outcome": "IMPL"})
4555
+ for row in nand_rows:
4556
+ outcomes.append({"point_id": row[0], "content": row[1], "confidence": float(row[2]), "outcome": "NAND"})
4557
+
4558
+ total = len(outcomes)
4559
+ impl_count = sum(1 for o in outcomes if o["outcome"] == "IMPL")
4560
+ nand_count = sum(1 for o in outcomes if o["outcome"] == "NAND")
4561
+
4562
+ if total == 0:
4563
+ return {"mean": 0.5, "total_events": 0, "impl_count": 0, "nand_count": 0,
4564
+ "alpha": 1.0, "beta": 1.0, "outcomes": []}
4565
+
4566
+ # Simple Beta reputation: IMPL = success, NAND = failure
4567
+ # Prior: Beta(1, 1) uniform
4568
+ alpha = 1.0 + impl_count
4569
+ beta = 1.0 + nand_count
4570
+ mean = alpha / (alpha + beta)
4571
+
4572
+ return {
4573
+ "mean": round(mean, 4),
4574
+ "total_events": total,
4575
+ "impl_count": impl_count,
4576
+ "nand_count": nand_count,
4577
+ "alpha": alpha,
4578
+ "beta": beta,
4579
+ "outcomes": outcomes[:20], # cap for readability
4580
+ }
4581
+
4582
+ def get_entity(self, id_val: str) -> dict:
4583
+ return self._get_entity(id_val)
4584
+
4585
+ def update_entity(self, id_val: str, **props) -> dict:
4586
+ _coerce_props(props) # accept MCP-style nested props= dict (#218)
4587
+ return self._update_entity(id_val, **props)
4588
+
4589
+ def delete_entity(self, id_val: str) -> bool:
4590
+ return self._delete_entity(id_val)
4591
+
4592
+ # ── Query Helpers ─────────────────────────────────────────────
4593
+
4594
+ def get_owned_entities(self, subject_id: str) -> list:
4595
+ """Return all entities owned by a Subject (governance query)."""
4596
+ proj = self._get_proj()
4597
+ # Issue #327: start from the labeled, indexed Subject (both id and name
4598
+ # are RANGE-indexed -> OR uses the index) and traverse ownedBy inward.
4599
+ # Narrowing: ownedBy/memberOf targets are canonically Subject (#216);
4600
+ # non-Subject targets are out of contract.
4601
+ r = proj.g.query(
4602
+ "MATCH (s:Subject) WHERE s.id = $sid OR s.name = $sid "
4603
+ "MATCH (s)<-[:ownedBy]-(e) RETURN properties(e) LIMIT 100",
4604
+ params={"sid": subject_id},
4605
+ )
4606
+ return [dict(row[0]) for row in r.result_set]
4607
+
4608
+ def get_provenance_chain(self, point_id: str) -> list:
4609
+ """Return full provenance chain for a Point."""
4610
+ proj = self._get_proj()
4611
+ r = proj.g.query(
4612
+ "MATCH (p:Point {id:$pid})-[:extractedFrom]->(src:Source)-[:references]->(entity) "
4613
+ "RETURN properties(src) as source, properties(entity) as entity, labels(entity) as labels LIMIT 1",
4614
+ params={"pid": point_id},
4615
+ )
4616
+ return [{"source": dict(row[0]), "entity": dict(row[1]), "labels": list(row[2])} for row in r.result_set]
4617
+
4618
+ def link_source_to_entity(self, source_url: str, entity_id: str, entity_label: str, source_kind: str = "document") -> None:
4619
+ """Create Source → Entity references edge (Ontology v3.1 §3.4).
4620
+
4621
+ Auto-creates the Source node if it doesn't exist (MERGE + ON CREATE SET)
4622
+ so the edge works even when no Point extracted the source yet (#205).
4623
+
4624
+ Args:
4625
+ source_url: the Source node's url (auto-created if missing)
4626
+ entity_id: the Document/Event/Object node id the source references
4627
+ entity_label: the entity label (Document|Event|Object) for the MATCH
4628
+ source_kind: sourceKind to set on auto-created Source (default: "document")
4629
+
4630
+ Raises:
4631
+ ValueError: if entity_label is not one of Document, Event, Object
4632
+ (Action was dissolved in Ontology v3.0).
4633
+ """
4634
+ proj = self._get_proj()
4635
+ proj.link_source_to_entity(source_url, entity_id, entity_label, source_kind)
4636
+
4637
+ def get_org_structure(self, subject_id: str) -> dict:
4638
+ """Return organisational structure: members, roles, sub-teams."""
4639
+ proj = self._get_proj()
4640
+ # Issue #327: labeled Subject start (id|name OR both indexed -> Index
4641
+ # Scan) then traverse outward; roles filters the source Subject p.
4642
+ members = proj.g.query(
4643
+ "MATCH (s:Subject) WHERE s.id = $sid OR s.name = $sid "
4644
+ "MATCH (p:Subject)-[:memberOf]->(s) RETURN properties(p)",
4645
+ params={"sid": subject_id},
4646
+ )
4647
+ roles = proj.g.query(
4648
+ "MATCH (p:Subject) WHERE p.id = $sid OR p.name = $sid "
4649
+ "MATCH (p)-[:holdsRole]->(r:Subject) RETURN properties(r)",
4650
+ params={"sid": subject_id},
4651
+ )
4652
+ return {
4653
+ "members": [dict(row[0]) for row in members.result_set],
4654
+ "roles": [dict(row[0]) for row in roles.result_set],
4655
+ }
4656
+
4657
+ def ulid(self) -> str:
4658
+ from .ids import ulid as _ulid
4659
+ return _ulid()
4660
+
4661
+ # ── Source Node Completion ────────────────────────────────────
4662
+
4663
+ def complete_source(self, url: str, content: str = None, external_id: str = None) -> dict:
4664
+ """Populate Source node fields: contentHash, version, externalId."""
4665
+ import hashlib
4666
+ proj = self._get_proj()
4667
+ updates = {}
4668
+ if content is not None:
4669
+ updates["contentHash"] = hashlib.sha256(content.encode()).hexdigest()
4670
+ if external_id is not None:
4671
+ updates["externalId"] = external_id
4672
+ # Increment version
4673
+ r = proj.g.query(
4674
+ "MATCH (s:Source {url:$url}) "
4675
+ "SET s.version = coalesce(s.version, 0) + 1, s.updatedAt = $now "
4676
+ "SET s += $updates "
4677
+ "RETURN properties(s)",
4678
+ params={"url": url, "updates": updates, "now": __import__('datetime').datetime.now(__import__('datetime').timezone.utc).isoformat()},
4679
+ )
4680
+ return dict(r.result_set[0][0]) if r.result_set else {}
4681
+
4682
+ # ── Backfill Migration ────────────────────────────────────────
4683
+
4684
+ def backfill_v25(self, dry_run: bool = False) -> dict:
4685
+ """Backfill existing tortoise.db to ONTOLOGY v2.5 schema."""
4686
+ proj = self._get_proj()
4687
+ report = {"dry_run": dry_run, "actions": []}
4688
+
4689
+ # 1. Backfill status on Points
4690
+ r = proj.g.query("MATCH (n:Point) WHERE n.status IS NULL RETURN count(n)")
4691
+ missing_status = r.result_set[0][0]
4692
+ if missing_status > 0:
4693
+ report["actions"].append(f"status_backfill: {missing_status} Points")
4694
+ if not dry_run:
4695
+ proj.g.query(f"MATCH (n:Point) WHERE n.status IS NULL SET n.status = 'live'")
4696
+
4697
+ # 2. Backfill pointKind
4698
+ r = proj.g.query("MATCH (n:Point) WHERE n.pointKind IS NULL RETURN count(n)")
4699
+ missing_kind = r.result_set[0][0]
4700
+ if missing_kind > 0:
4701
+ report["actions"].append(f"pointKind_backfill: {missing_kind} Points")
4702
+ if not dry_run:
4703
+ proj.g.query("MATCH (n:Point) WHERE n.pointKind IS NULL SET n.pointKind = 'statement'")
4704
+
4705
+ # 3. Count existing edges
4706
+ r = proj.g.query("MATCH ()-[r]->() RETURN count(r)")
4707
+ report["edge_count"] = r.result_set[0][0]
4708
+
4709
+ # 4. Verify Point count unchanged
4710
+ r = proj.g.query("MATCH (n:Point) RETURN count(n)")
4711
+ report["point_count"] = r.result_set[0][0]
4712
+
4713
+ return report