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/api.py ADDED
@@ -0,0 +1,303 @@
1
+ """EventAPI — the shared append surface both producers write through.
2
+
3
+ Attribution (`initiated_by`, `agent_id`) is bound once at construction, so the
4
+ extractor gets initiated_by="extractor" and a user-agent gets "user" without
5
+ per-call bookkeeping (see README Interaction model).
6
+
7
+ Every mutation appends exactly one event to the log AND (if a projection is
8
+ attached) applies it incrementally, so the store never drifts from the log.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from .idempotency import IngestKey, IngestResult
13
+ from .ids import now_iso, ulid
14
+ from .projection import fold
15
+
16
+
17
+ def provenance(source_id, span, quote, *, speaker=None, extracted_by="mock@0"):
18
+ return {
19
+ "source_id": source_id,
20
+ "speaker": speaker,
21
+ "span": span,
22
+ "quote": quote,
23
+ "extracted_by": extracted_by,
24
+ "extracted_at": now_iso(),
25
+ }
26
+
27
+
28
+ class EventAPI:
29
+ def __init__(self, log, *, initiated_by: str, agent_id: str | None = None,
30
+ projection=None):
31
+ assert initiated_by in ("extractor", "user")
32
+ self.log = log
33
+ self.initiated_by = initiated_by
34
+ self.agent_id = agent_id
35
+ self.projection = projection
36
+ self.current_run: str | None = None
37
+ self._ingest_cache: dict[tuple, str] | None = None
38
+ # Gate 4: SVBP instance (lazy-init on first confidence query)
39
+ self._svbp = None
40
+
41
+ # -- internals -----------------------------------------------------------
42
+ def _emit(self, type_: str, *, corrects=None, **payload) -> dict:
43
+ event = {
44
+ "event_id": ulid(),
45
+ "ts": now_iso(),
46
+ "type": type_,
47
+ "initiated_by": self.initiated_by,
48
+ "agent_id": self.agent_id,
49
+ "corrects": corrects,
50
+ **payload,
51
+ }
52
+ self.log.append(event)
53
+ if self.projection is not None:
54
+ self.projection.apply(event)
55
+ return event
56
+
57
+ def _point(self, content, provenance, operator=None) -> dict:
58
+ prov = dict(provenance)
59
+ prov.setdefault("run_id", self.current_run)
60
+ # #49 Phase 2: context param removed — context is deprecated.
61
+ # Context/domain is now tracked via pointKind + provenance extractedFrom.
62
+ return {
63
+ "id": ulid(),
64
+ "content": content,
65
+ "operator": operator,
66
+ "provenance": prov,
67
+ "status": "live",
68
+ "createdAt": now_iso(),
69
+ }
70
+
71
+ # -- ingest lifecycle / idempotency gate --------------------------------
72
+ def begin_ingest(self, source_id, extractor_version, key: IngestKey, *,
73
+ force: bool = False) -> IngestResult:
74
+ # Lazy-cache IngestStarted events: scan the log once, then O(1) lookups.
75
+ if self._ingest_cache is None:
76
+ self._ingest_cache = {}
77
+ for e in self.log.read_all():
78
+ if e["type"] == "IngestStarted":
79
+ k = e["key"]
80
+ self._ingest_cache[
81
+ (k["kind"], k["value"], e["extractor_version"])
82
+ ] = e["run_id"]
83
+
84
+ cache_key = (key.kind, key.value, extractor_version)
85
+ if cache_key in self._ingest_cache and not force:
86
+ self.current_run = None
87
+ return IngestResult(run_id=self._ingest_cache[cache_key], skip=True,
88
+ reason="already processed (same key + extractor_version)")
89
+
90
+ # Reprocess (new version or --force): supersede every prior run for this
91
+ # key, whatever its version, so the latest run wins.
92
+ superseded = [
93
+ rid for ck, rid in self._ingest_cache.items()
94
+ if ck[:2] == (key.kind, key.value)
95
+ ]
96
+ run_id = ulid()
97
+ if superseded: # reprocess: retract the superseded runs' points first
98
+ points = fold(self.log.read_all())
99
+ for p in list(points.values()):
100
+ if p["provenance"].get("run_id") in superseded:
101
+ self._emit("PointRetracted", id=p["id"])
102
+ self._emit("IngestStarted", run_id=run_id, source_id=source_id,
103
+ extractor_version=extractor_version, key=key.as_dict(),
104
+ supersedes=superseded or None)
105
+ # Update cache with the new run.
106
+ self._ingest_cache[cache_key] = run_id
107
+ self.current_run = run_id
108
+ return IngestResult(run_id=run_id, skip=False)
109
+
110
+ # -- mutations ----------------------------------------------------------
111
+ def add_point(self, content, provenance, *, corrects=None, **fields) -> str:
112
+ p = self._point(content, provenance)
113
+ p.update(fields)
114
+ # P1 #49: mark events with projection_version=2 so the projection gate
115
+ # (Task 1.6) knows to strip context from v2 events.
116
+ self._emit("PointAdded", point=p, corrects=corrects, projection_version=2)
117
+ # Auto-compute grounding when a resolution event seeds the a-vector (#6704).
118
+ # P1 #49: check pointKind, not context (context is deprecated).
119
+ # ponytail: duck-typed; add a proper protocol if more backends gain grounding.
120
+ pk = p.get("pointKind") or fields.get("pointKind")
121
+ if pk == "resolution-event" and self.projection is not None:
122
+ if hasattr(self.projection, "compute_grounding"):
123
+ self.projection.compute_grounding()
124
+ return p["id"]
125
+
126
+ def add_operator(self, op_type, inputs, provenance, *,
127
+ content=None, corrects=None) -> str:
128
+ assert op_type in ("NAND", "IMPL"), f"unknown gate {op_type!r}"
129
+ _inputs = [x["id"] if isinstance(x, dict) and "id" in x
130
+ else x.id if hasattr(x, "id") else x
131
+ for x in inputs]
132
+ label = content or f"{op_type}({', '.join(_inputs)})"
133
+ p = self._point(label, provenance,
134
+ operator={"op_type": op_type, "inputs": _inputs})
135
+ self._emit("OperatorAdded", point=p, corrects=corrects, projection_version=2)
136
+
137
+ # Gate 4: incrementally update SVBP on the new operator
138
+ # ponytail: only FalkorProjection supports SVBP; InMemoryProjection doesn't.
139
+ if self.projection is not None and hasattr(self.projection, 'get_svbp'):
140
+ # Lazy-init SVBP if not yet created (handles operators added
141
+ # before any get_confidence() call — Bug 5 fix).
142
+ if self._svbp is None:
143
+ svbp = self.projection.get_svbp(
144
+ n_particles=25, n_svgd_steps=15, svgd_lr=0.01,
145
+ damping=0.5, max_iter=40, tol=5e-3, seed=42,
146
+ )
147
+ if svbp is not None:
148
+ self._svbp = svbp
149
+ if self._svbp is not None:
150
+ factors, _ = self.projection.extract_svbp_factors()
151
+ if factors:
152
+ old_max = self._svbp.max_iter
153
+ self._svbp.max_iter = 5
154
+ try:
155
+ self._svbp.run(factors, warm_start=True)
156
+ finally:
157
+ self._svbp.max_iter = old_max # Bug 4 fix
158
+
159
+ return p["id"]
160
+
161
+ # ── Gate 4: Confidence API ────────────────────────────────────
162
+
163
+ def get_confidence(self, point_id: str) -> dict | None:
164
+ """Compute confidence for a point via SVBP.
165
+
166
+ Lazy-inits SVBP on first call. Returns {mean, variance, alpha, beta}
167
+ or None if the projection doesn't support SVBP.
168
+ """
169
+ if self._svbp is None and self.projection is not None and hasattr(self.projection, 'get_svbp'):
170
+ svbp = self.projection.get_svbp(
171
+ n_particles=25, n_svgd_steps=15, svgd_lr=0.01,
172
+ damping=0.5, max_iter=40, tol=5e-3, seed=42,
173
+ )
174
+ if svbp is not None:
175
+ self._svbp = svbp
176
+ if self._svbp is None:
177
+ return None
178
+ return self._svbp.compute_confidence(point_id)
179
+
180
+ def revise_point(self, id, *, new_content=None, corrects) -> str:
181
+ ev = self._emit("PointRevised", id=id, new_content=new_content,
182
+ corrects=corrects)
183
+ return ev["event_id"]
184
+
185
+ def retract_point(self, id, *, corrects) -> str:
186
+ ev = self._emit("PointRetracted", id=id, corrects=corrects)
187
+ return ev["event_id"]
188
+
189
+ def merge_points(self, keep_id, merge_ids, *, corrects=None) -> str:
190
+ ev = self._emit("PointsMerged", keep_id=keep_id, merge_ids=list(merge_ids),
191
+ corrects=corrects)
192
+ return ev["event_id"]
193
+
194
+ def add_subject(self, name: str, subject_kind: str = "other") -> str:
195
+ """Emit SubjectAdded event. Returns the subject's id."""
196
+ sid = ulid()
197
+ self._emit("SubjectAdded", id=sid, name=name,
198
+ subject_kind=subject_kind,
199
+ createdAt=now_iso())
200
+ return sid
201
+
202
+ def add_object(self, name: str, object_kind: str = "other") -> str:
203
+ """Emit ObjectRegistered event. Returns the object's id."""
204
+ oid = ulid()
205
+ self._emit("ObjectRegistered", id=oid, name=name,
206
+ object_kind=object_kind,
207
+ createdAt=now_iso())
208
+ return oid
209
+
210
+ def add_document(self, doc_id: str, title: str, *,
211
+ document_kind: str = "",
212
+ document_knowledge_domain: str = "",
213
+ about_entities: list[str] | None = None,
214
+ authored_by: str = "",
215
+ owned_by: str = "",
216
+ managed_by: str = "",
217
+ governing_agreement: str = "",
218
+ doc_status: str = "draft",
219
+ format: str = "markdown",
220
+ version: str = "",
221
+ createdAt: str | None = None,
222
+ updatedAt: str | None = None,
223
+ corrects: str | None = None,
224
+ topics: list[str] | None = None,
225
+ summary: str | None = None,
226
+ session_id: str | None = None,
227
+ event_id: str | None = None,
228
+ source_path: str | None = None,
229
+ needs_extraction: bool = False) -> str:
230
+ """Emit DocumentCreated event. Returns the document id (same as input).
231
+
232
+ JSONL fields are snake_case per plan §4.3 convention.
233
+ Projection normalizes to camelCase for the graph.
234
+ #125: topics/summary/session_id/event_id capture metadata.
235
+ #167: source_path → d.sourcePath for file resolution.
236
+ #133: needs_extraction → d.needs_extraction for --upgrade-all discovery.
237
+ """
238
+ self._emit("DocumentCreated",
239
+ corrects=corrects,
240
+ id=doc_id,
241
+ title=title,
242
+ document_kind=document_kind,
243
+ document_knowledge_domain=document_knowledge_domain,
244
+ about_entities=about_entities or [],
245
+ authored_by=authored_by,
246
+ owned_by=owned_by,
247
+ managed_by=managed_by,
248
+ governing_agreement=governing_agreement,
249
+ doc_status=doc_status,
250
+ format=format,
251
+ version=version,
252
+ createdAt=createdAt or now_iso(),
253
+ updatedAt=updatedAt or now_iso(),
254
+ topics=topics or [],
255
+ summary=summary,
256
+ session_id=session_id,
257
+ event_id=event_id,
258
+ source_path=source_path,
259
+ needs_extraction=needs_extraction)
260
+ return doc_id
261
+
262
+ def add_event(self, event_id: str, event_kind: str, *,
263
+ subject: str = "",
264
+ object_name: str = "",
265
+ object_type: str = "",
266
+ uses: list | None = None,
267
+ participants: list[str] | None = None,
268
+ started_at: str = "",
269
+ ended_at: str = "",
270
+ classification_level: str = "internal",
271
+ format: str = "jsonl",
272
+ **extra) -> str:
273
+ """Emit an EventRecorded event (#125). Returns the event id.
274
+
275
+ The event id is passed as ``id`` (not ``eventId``) to match the
276
+ projection's ``_upsert_event`` lookup (``inner.get("id") or
277
+ inner.get("eventId")``).
278
+ """
279
+ self._emit("EventRecorded",
280
+ id=event_id,
281
+ eventKind=event_kind,
282
+ subject=subject,
283
+ object=object_name,
284
+ objectType=object_type,
285
+ uses=uses or [],
286
+ participants=participants or [],
287
+ startedAt=started_at,
288
+ endedAt=ended_at,
289
+ classificationLevel=classification_level,
290
+ format=format,
291
+ **extra)
292
+ return event_id
293
+
294
+ # ── Cleanup ───────────────────────────────────────────────────
295
+
296
+ def close(self):
297
+ """Release SVBP particles and close projection."""
298
+ if self._svbp is not None:
299
+ self._svbp._particles.clear()
300
+ self._svbp._summaries.clear()
301
+ self._svbp = None
302
+ if self.projection is not None and hasattr(self.projection, 'close'):
303
+ self.projection.close()
@@ -0,0 +1,31 @@
1
+ """ARCHIVED: Legacy search() implementation from before Phase 0 hybrid search (#7748).
2
+
3
+ Removed 2026-08-03. Replaced by tortoise_fts_query().
4
+ This code is preserved for reference only — do not import from here.
5
+ """
6
+
7
+ # The search() method was removed from TortoiseSDK.
8
+ # It performed in-memory TF-IDF / sentence-transformers search over all Points.
9
+ #
10
+ # Migration:
11
+ # sdk.search(q, kind=k, context=c) → sdk.tortoise_fts_query(q, kind=k, context=c)
12
+ #
13
+ # The new method returns SearchResult dicts with:
14
+ # - RRF fusion of FTS + vector + structural indexes
15
+ # - EP breakdown (confidence_mean, evidence, contention)
16
+ # - match_source field
17
+ # - Full-scan mode when query is None + context is set
18
+
19
+ # Original implementation (for reference):
20
+ #
21
+ # def search(self, query: str, kind: str | None = None,
22
+ # context: str | None = None, *,
23
+ # threshold: float = 0.3, limit: int = 10) -> list[dict]:
24
+ # """Semantic/vector search over Points."""
25
+ # if limit < 1:
26
+ # raise ValueError(f"limit must be >= 1, got {limit}")
27
+ # if not (0.0 <= threshold <= 1.0):
28
+ # raise ValueError(f"threshold must be 0.0-1.0, got {threshold}")
29
+ # from .embeddings import search_points
30
+ # points = self.query(kind=kind, context=context)
31
+ # return search_points(query, points, threshold=threshold, limit=limit)
tortoise/audit.py ADDED
@@ -0,0 +1,236 @@
1
+ """Graph audit — check Tortoise graph wiring quality.
2
+
3
+ Identifies: missing sourceKind, missing sourceDate, superseded gaps,
4
+ edge type errors, and mitigation opportunities.
5
+
6
+ Usage:
7
+ from tortoise.audit import audit_graph
8
+ result = audit_graph(proj, 'criteria')
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+
14
+
15
+ @dataclass
16
+ class AuditIssue:
17
+ issue_type: str # missing_sourceKind, missing_sourceDate, superseded_no_edge, etc.
18
+ severity: str # high, medium, low
19
+ node_id: str | None = None
20
+ detail: str = ""
21
+ fix: str = ""
22
+
23
+
24
+ @dataclass
25
+ class AuditResult:
26
+ issues: list[AuditIssue] = field(default_factory=list)
27
+ node_count: int = 0
28
+ edge_count: int = 0
29
+
30
+ def high_count(self) -> int:
31
+ return sum(1 for i in self.issues if i.severity == "high")
32
+
33
+ def medium_count(self) -> int:
34
+ return sum(1 for i in self.issues if i.severity == "medium")
35
+
36
+ def low_count(self) -> int:
37
+ return sum(1 for i in self.issues if i.severity == "low")
38
+
39
+
40
+ def audit_graph(proj, point_kinds: list[str] | None = None) -> AuditResult:
41
+ """Audit graph wiring for the given pointKind(s).
42
+
43
+ Args:
44
+ proj: FalkorProjection instance
45
+ point_kinds: Optional list of pointKind values to scope the audit.
46
+ If None, all Points are audited (no filter applied).
47
+ """
48
+ if point_kinds is None:
49
+ kinds = [] # empty = audit all (no filter)
50
+ else:
51
+ kinds = point_kinds
52
+
53
+ def _kinds_w(alias: str = "n") -> str:
54
+ """Build pointKind WHERE clause for the given node alias, parenthesized."""
55
+ if not kinds:
56
+ return "TRUE"
57
+ return f"{alias}.pointKind IN $kinds"
58
+
59
+ def _op_in_kinds(alias: str = "op", tgt_alias: str = "tgt") -> str:
60
+ """pointKind WHERE for operators — matches by own pointKind or target's."""
61
+ if not kinds:
62
+ return "TRUE"
63
+ own = _kinds_w(alias)
64
+ tgt_q = f"{tgt_alias}.pointKind IN $kinds"
65
+ return f"({own} OR {tgt_q})"
66
+
67
+ issues: list[AuditIssue] = []
68
+
69
+ # ── 0. Count nodes/edges in scope ──────────────────────────────
70
+ r = proj.g.query(f"MATCH (n:Point) WHERE {_kinds_w('n')} RETURN count(n)", params={"kinds": kinds})
71
+ node_count = r.result_set[0][0] if r.result_set else 0
72
+
73
+ # Count edges TO context-scoped points (correct traversal: operator -> point)
74
+ r = proj.g.query(
75
+ f"MATCH (n:Point) WHERE {_kinds_w('n')} "
76
+ f"OPTIONAL MATCH (op:Point)-[e:IMPL|NAND]->(n) RETURN count(e)",
77
+ params={"kinds": kinds},
78
+ )
79
+ edge_count = r.result_set[0][0] if r.result_set else 0
80
+
81
+ # ── 1a. missing_sourceKind via operators (medium) ──────────────
82
+ # Operators in scope connecting to evidence without source tier.
83
+ # Match operators by own context (post-#130) OR target context (pre-#130 compat).
84
+ r = proj.g.query(
85
+ f"MATCH (op:Point {{is_operator: true}})-[:IMPL|NAND]->(ev:Point)\n"
86
+ f"WHERE {_op_in_kinds('op', 'ev')}\n"
87
+ "AND ev.sourceKind IS NULL AND (ev.is_operator IS NULL OR ev.is_operator = false)\n"
88
+ "RETURN DISTINCT op.id, ev.id, ev.content LIMIT 50",
89
+ params={"kinds": kinds},
90
+ )
91
+ for row in r.result_set:
92
+ op_id, ev_id, ev_content = row[0], row[1], (row[2] or "")[:80]
93
+ issues.append(AuditIssue(
94
+ issue_type="missing_sourceKind",
95
+ severity="medium",
96
+ node_id=str(ev_id),
97
+ detail=f"Evidence '{ev_content}' (from operator {op_id}) has no sourceKind",
98
+ # #398: Point-level sourceKind tier annotations are legacy — tier the
99
+ # SOURCE node instead (source-level inheritance benefits all points).
100
+ fix=f"tier the source backing this point via "
101
+ f"tortoise_set_source_tier(url, 'T0'..'T4') or create_source(url, kind, tier=...)",
102
+ ))
103
+
104
+ # ── 2. missing_sourceDate (low) ─────────────────────────────────
105
+ r = proj.g.query(
106
+ f"MATCH (ev:Point) WHERE {_kinds_w('ev')}\n"
107
+ "AND ev.sourceKind IS NOT NULL AND ev.sourceDate IS NULL\n"
108
+ "RETURN ev.id, ev.content, ev.sourceKind LIMIT 50",
109
+ params={"kinds": kinds},
110
+ )
111
+ for row in r.result_set:
112
+ ev_id, ev_content, sk = row[0], (row[1] or "")[:80], row[2]
113
+ issues.append(AuditIssue(
114
+ issue_type="missing_sourceDate",
115
+ severity="low",
116
+ node_id=str(ev_id),
117
+ detail=f"'{ev_content}' has sourceKind={sk} but no sourceDate",
118
+ fix=f"MATCH (n:Point {{id:'{ev_id}'}}) SET n.sourceDate = '2026-01-01'",
119
+ ))
120
+
121
+ # ── 3. superseded_no_edge (high) ──────────────────────────────
122
+ r = proj.g.query(
123
+ f"MATCH (n:Point) WHERE {_kinds_w('n')} AND n.status = 'superseded'\n"
124
+ "OPTIONAL MATCH (n)-[s:SUPERSEDES]->(:Point)\n"
125
+ "WITH n, s WHERE s IS NULL\n"
126
+ "RETURN n.id, n.content LIMIT 50",
127
+ params={"kinds": kinds},
128
+ )
129
+ for row in r.result_set:
130
+ nid, content = row[0], (row[1] or "")[:80]
131
+ issues.append(AuditIssue(
132
+ issue_type="superseded_no_edge",
133
+ severity="high",
134
+ node_id=str(nid),
135
+ detail=f"Superseded point '{content}' has no :SUPERSEDES edge",
136
+ fix=f"MATCH (old:Point {{id:'{nid}'}}), (new:Point {{id:'<replacement>'}})\n"
137
+ "CREATE (old)-[:SUPERSEDES]->(new)",
138
+ ))
139
+
140
+ # ── 4. superseded_active_edges (medium) ──────────────────────
141
+ r = proj.g.query(
142
+ f"MATCH (sup:Point) WHERE {_kinds_w('sup')} AND sup.status = 'superseded'\n"
143
+ "MATCH (sup)<-[r:IMPL|NAND]-(active:Point {status: 'live'})\n"
144
+ "RETURN DISTINCT sup.id, sup.content, type(r), active.id LIMIT 50",
145
+ params={"kinds": kinds},
146
+ )
147
+ for row in r.result_set:
148
+ sup_id, sup_content, edge_type, active_id = row[0], (row[1] or "")[:80], row[2], row[3]
149
+ issues.append(AuditIssue(
150
+ issue_type="superseded_active_edges",
151
+ severity="medium",
152
+ node_id=str(sup_id),
153
+ detail=f"Superseded '{sup_content}' has active {edge_type} edge from {active_id}",
154
+ fix=f"Remove edges from '{sup_id}' or mark {active_id} as superseded too",
155
+ ))
156
+
157
+ # ── 5. impl_instead_of_nand (high) ──────────────────────────
158
+ contradiction_keywords = ["not ", "fail", "cannot", "no ", "never", "impossible", "contradict"]
159
+ seen_impl_nand = set()
160
+ for kw in contradiction_keywords:
161
+ # Match by source context OR by target context (operators may lack context pre-#130)
162
+ r = proj.g.query(
163
+ f"MATCH (src:Point)-[e:IMPL]->(tgt:Point)\n"
164
+ f"WHERE {_op_in_kinds('src', 'tgt')}\n"
165
+ f"AND toLower(tgt.content) CONTAINS '{kw}' AND tgt.is_operator IS NULL\n"
166
+ "RETURN src.id, tgt.id, tgt.content LIMIT 20",
167
+ params={"kinds": kinds},
168
+ )
169
+ for row in r.result_set:
170
+ src_id, tgt_id, tgt_content = row[0], row[1], (row[2] or "")[:80]
171
+ key = (str(src_id), str(tgt_id))
172
+ if key not in seen_impl_nand:
173
+ seen_impl_nand.add(key)
174
+ issues.append(AuditIssue(
175
+ issue_type="impl_instead_of_nand",
176
+ severity="high",
177
+ node_id=str(src_id),
178
+ detail=f"IMPL edge {src_id} → '{tgt_content}' (keyword: '{kw}') — may need NAND",
179
+ fix=f"Verify semantic contradiction, then: tortoise_create_operator('NAND', '{src_id}', ['{tgt_id}'])",
180
+ ))
181
+
182
+ # ── 6. mitigation_recommended (medium) ──────────────────────
183
+ r = proj.g.query(
184
+ f"MATCH (op:Point {{is_operator: true}})-[:IMPL|NAND]->(tgt:Point)\n"
185
+ f"WHERE {_op_in_kinds('op', 'tgt')} AND op.confidence <= 0.35\n"
186
+ "OPTIONAL MATCH (tgt)<-[mit:mitigates]-(:Point)\n"
187
+ "WITH op, tgt, mit WHERE mit IS NULL\n"
188
+ "RETURN DISTINCT op.id, op.confidence, tgt.content LIMIT 50",
189
+ params={"kinds": kinds},
190
+ )
191
+ for row in r.result_set:
192
+ op_id, conf, tgt_content = row[0], row[1], (row[2] or "")[:80]
193
+ issues.append(AuditIssue(
194
+ issue_type="mitigation_recommended",
195
+ severity="medium",
196
+ node_id=str(op_id),
197
+ detail=f"Low-confidence operator {op_id} (conf={conf}) → '{tgt_content}' has no mitigation",
198
+ fix=f"tortoise_mitigate_operator('{op_id}', 'Relevant because...', confidence=0.7)",
199
+ ))
200
+
201
+ return AuditResult(
202
+ issues=issues,
203
+ node_count=node_count,
204
+ edge_count=edge_count,
205
+ )
206
+
207
+
208
+ def print_audit(result: AuditResult) -> None:
209
+ """Pretty-print audit results."""
210
+ print(f"\n{'='*60}")
211
+ print(f"Tortoise Audit — {result.node_count} nodes, {result.edge_count} edges")
212
+ print(f"Scope: {result.node_count} nodes, {result.edge_count} edges")
213
+ print(f"Issues: {len(result.issues)} total "
214
+ f"({result.high_count()} high, {result.medium_count()} medium, {result.low_count()} low)")
215
+ print(f"{'='*60}")
216
+
217
+ if not result.issues:
218
+ print("\n✅ No issues found.")
219
+ return
220
+
221
+ for severity in ["high", "medium", "low"]:
222
+ sev_issues = [i for i in result.issues if i.severity == severity]
223
+ if not sev_issues:
224
+ continue
225
+ print(f"\n── {severity.upper()} ({len(sev_issues)}) ──")
226
+ by_type: dict[str, list[AuditIssue]] = {}
227
+ for iss in sev_issues:
228
+ by_type.setdefault(iss.issue_type, []).append(iss)
229
+ for itype, items in by_type.items():
230
+ print(f"\n [{itype}] — {len(items)} instances")
231
+ for iss in items[:5]:
232
+ print(f" • {iss.detail[:120]}")
233
+ if iss.fix:
234
+ print(f" fix: {iss.fix[:120]}")
235
+ if len(items) > 5:
236
+ print(f" … and {len(items) - 5} more")