tortoise-graph 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. tortoise/__init__.py +45 -0
  2. tortoise/__main__.py +1865 -0
  3. tortoise/analyze.py +473 -0
  4. tortoise/api.py +303 -0
  5. tortoise/archived/search_legacy.py +31 -0
  6. tortoise/audit.py +236 -0
  7. tortoise/audit_events.py +284 -0
  8. tortoise/auth.py +107 -0
  9. tortoise/backup.py +155 -0
  10. tortoise/config.py +99 -0
  11. tortoise/connector_loader.py +74 -0
  12. tortoise/connectors/__init__.py +5 -0
  13. tortoise/connectors/github.py +432 -0
  14. tortoise/connectors/github_docs.py +146 -0
  15. tortoise/connectors/linear.py +199 -0
  16. tortoise/connectors/slack.py +222 -0
  17. tortoise/consistency.py +132 -0
  18. tortoise/crypto.py +52 -0
  19. tortoise/deployment.py +62 -0
  20. tortoise/domain_loader.py +142 -0
  21. tortoise/dream.py +153 -0
  22. tortoise/embedded_reaper.py +744 -0
  23. tortoise/embeddings.py +227 -0
  24. tortoise/ep.py +534 -0
  25. tortoise/exceptions.py +16 -0
  26. tortoise/extractor.py +945 -0
  27. tortoise/hosted_api.py +1982 -0
  28. tortoise/hosted_middleware.py +22 -0
  29. tortoise/idempotency.py +39 -0
  30. tortoise/ids.py +23 -0
  31. tortoise/indexer/github_indexer.py +129 -0
  32. tortoise/ingest.py +614 -0
  33. tortoise/log.py +29 -0
  34. tortoise/m0.py +50 -0
  35. tortoise/mcp_auth.py +337 -0
  36. tortoise/mcp_client.py +108 -0
  37. tortoise/mcp_server.py +1356 -0
  38. tortoise/memory_orchestrator.py +492 -0
  39. tortoise/memory_scope.py +15 -0
  40. tortoise/migrate_db.py +244 -0
  41. tortoise/migrate_kinds.py +141 -0
  42. tortoise/mining.py +338 -0
  43. tortoise/models.py +109 -0
  44. tortoise/monitoring.py +133 -0
  45. tortoise/navigation.py +216 -0
  46. tortoise/pack_registry.py +767 -0
  47. tortoise/pipeline_cli.py +197 -0
  48. tortoise/projection/__init__.py +913 -0
  49. tortoise/projection/edges.py +311 -0
  50. tortoise/projection/entities.py +521 -0
  51. tortoise/projection/grounding.py +95 -0
  52. tortoise/projection/propagation.py +114 -0
  53. tortoise/projection.py +37 -0
  54. tortoise/quadrature.py +90 -0
  55. tortoise/query_suggestions.py +194 -0
  56. tortoise/quota.py +163 -0
  57. tortoise/ranking.py +280 -0
  58. tortoise/render.py +108 -0
  59. tortoise/scripts/manifest.py +67 -0
  60. tortoise/sdk.py +4713 -0
  61. tortoise/search_engine.py +887 -0
  62. tortoise/security.py +268 -0
  63. tortoise/selfhost.py +157 -0
  64. tortoise/selfhost_api.py +201 -0
  65. tortoise/session_continuity.py +82 -0
  66. tortoise/session_indexer.py +569 -0
  67. tortoise/shared_state/__init__.py +20 -0
  68. tortoise/shared_state/concurrency.py +113 -0
  69. tortoise/shared_state/event_log.py +192 -0
  70. tortoise/shared_state/events.py +150 -0
  71. tortoise/shared_state/monitoring.py +87 -0
  72. tortoise/shared_state/recovery.py +126 -0
  73. tortoise/shared_state/tests/__init__.py +15 -0
  74. tortoise/shared_state/tests/test_concurrency.py +123 -0
  75. tortoise/shared_state/tests/test_events.py +145 -0
  76. tortoise/shared_state/tests/test_monitoring.py +54 -0
  77. tortoise/shared_state/tests/test_recovery.py +181 -0
  78. tortoise/source_credibility.py +306 -0
  79. tortoise/svbp.py +446 -0
  80. tortoise/taxonomy.py +71 -0
  81. tortoise/test_cross_ontology.py +180 -0
  82. tortoise/test_tortoise_client.py +206 -0
  83. tortoise/tool_registry.py +805 -0
  84. tortoise/tortoise_client.py +262 -0
  85. tortoise/verify_ontology.py +154 -0
  86. tortoise/version_vector.py +97 -0
  87. tortoise/weights.py +61 -0
  88. tortoise_graph-0.2.0.dist-info/METADATA +152 -0
  89. tortoise_graph-0.2.0.dist-info/RECORD +93 -0
  90. tortoise_graph-0.2.0.dist-info/WHEEL +5 -0
  91. tortoise_graph-0.2.0.dist-info/entry_points.txt +4 -0
  92. tortoise_graph-0.2.0.dist-info/licenses/LICENSE +95 -0
  93. tortoise_graph-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,767 @@
1
+ """Pack Registry — catalogs expansion packs from packs/*/manifest.yaml.
2
+
3
+ Loads all manifests at startup (no code execution). Validates against schema.
4
+ Provides queryable registry: "what packs are installed?" without importing connectors.
5
+
6
+ Design:
7
+ - Manifest-first: parse YAML only. No connector code executed on load.
8
+ - Idempotent: safe to re-run register(). Duplicates are skipped.
9
+ - Independent layers: ontology, connector status, and tools are queryable separately.
10
+ - Namespace enforcement: all kinds are prefixed with pack namespace on registration.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import dataclasses
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import yaml
19
+
20
+ # ── Canonical kind vocabularies (ONTOLOGY_v2.5 §1.1) ──────────────────────
21
+
22
+ CANONICAL_OBJECT_KINDS = frozenset({
23
+ # Core work concepts
24
+ "Project", "WorkItem",
25
+ # Universal
26
+ "document", "user", "skill", "tool", "agent",
27
+ "workflow", "agreement", "standard", "other",
28
+ })
29
+
30
+ CANONICAL_EVENT_KINDS = frozenset({
31
+ "meeting", "decision", "experiment", "deployment", "review",
32
+ "friction", "extraction", "documentCreated", "roleCreated", "pointAdded",
33
+ "sessionCaptured", # #125 metadata-only session capture
34
+ })
35
+
36
+ CANONICAL_POINT_KINDS = frozenset({
37
+ "statement", "decision", "vision", "strategy", "plan", "goal",
38
+ "target", "observation", "hypothesis",
39
+ })
40
+
41
+ CANONICAL_DOCUMENT_KINDS = frozenset({
42
+ "research", "reflectPostmortem", "strategyDoc", "visionDoc",
43
+ "planDoc", "decisionDoc", "meetingNotes", "experimentResults",
44
+ "evidenceLog", "handoff", "transcript", "roadmap", "brief",
45
+ })
46
+
47
+ # DEPRECATED (#122): CANONICAL_ACTION_KINDS is no longer canonical.
48
+ # Action kinds are still valid in pack manifests but the centralized 17-value
49
+ # frozenset is unnecessary — packs declare their own actionKinds.
50
+ # Kept for backward compatibility; will be removed in a future version.
51
+ CANONICAL_ACTION_KINDS = frozenset({
52
+ "research", "scope", "plan", "implement", "verify", "reflect",
53
+ "decompose", "delegate", "loop", "brainstorm", "decide", "agree",
54
+ "meet", "experiment", "deploy", "review", "other",
55
+ })
56
+
57
+ VALID_ENTITY_TYPES = frozenset({
58
+ "Subject", "Object", "Action", "Point", "Event", "Document", "Source",
59
+ })
60
+
61
+ VALID_CARDINALITIES = frozenset({
62
+ "one_to_one", "one_to_many", "many_to_one", "many_to_many",
63
+ })
64
+
65
+ VALID_PARAM_TYPES = frozenset({
66
+ "string", "integer", "number", "boolean", "array", "object",
67
+ })
68
+
69
+ CANONICAL_KINDS = {
70
+ "objectKinds": CANONICAL_OBJECT_KINDS,
71
+ "eventKinds": CANONICAL_EVENT_KINDS,
72
+ "pointKinds": CANONICAL_POINT_KINDS,
73
+ "documentKinds": CANONICAL_DOCUMENT_KINDS,
74
+ # "actionKinds": CANONICAL_ACTION_KINDS, # DEPRECATED (#122)
75
+ }
76
+
77
+
78
+ # ── Pack data model ───────────────────────────────────────────────────────
79
+
80
+ @dataclasses.dataclass
81
+ class PackManifest:
82
+ """Parsed manifest for one expansion pack."""
83
+ namespace: str
84
+ name: str
85
+ version: str
86
+ tier: str
87
+ description: str
88
+ path: Path
89
+
90
+ # Ontology
91
+ object_kinds: list[str] = dataclasses.field(default_factory=list)
92
+ event_kinds: list[str] = dataclasses.field(default_factory=list)
93
+ point_kinds: list[str] = dataclasses.field(default_factory=list)
94
+ document_kinds: list[str] = dataclasses.field(default_factory=list)
95
+ action_kinds: list[str] = dataclasses.field(default_factory=list)
96
+ relations: list[dict] = dataclasses.field(default_factory=list)
97
+
98
+ # Subclass declarations: {kind: parent_kind} — e.g., {"epic": "Project"}
99
+ # Parent must exist in core CANONICAL_OBJECT_KINDS or another pack's kinds.
100
+ kind_subclasses: dict[str, str] = dataclasses.field(default_factory=dict)
101
+
102
+ # Equivalence declarations: {kind: [other_ns:kind, ...]} — e.g., {"issue": ["pm:task"]}
103
+ # Means "this pack's 'issue' is the same concept as 'pm:task'."
104
+ # Bidirectional: the registry makes it symmetric at query time.
105
+ kind_equivalences: dict[str, list[str]] = dataclasses.field(default_factory=dict)
106
+
107
+ # Relations: edge schema declarations
108
+ # New format (preferred): {predicate, fromKind, toKind, mechanism, cardinality?}
109
+ # - predicate: domain verb — "addresses", "competesWith", "implements"
110
+ # - fromKind/toKind: specific pack kinds — "product-strategy:feature"
111
+ # - mechanism: IMPL or NAND — epistemic mechanism
112
+ # - cardinality: optional (one_to_one, one_to_many, many_to_one, many_to_many)
113
+ # Old format (compat): {predicate, from, to, cardinality?}
114
+ # - from/to: entity types — "Object", "Subject"
115
+
116
+ # Connectors
117
+ connectors: list[dict] = dataclasses.field(default_factory=list)
118
+
119
+ # Tools
120
+ tools: list[dict] = dataclasses.field(default_factory=list)
121
+
122
+ # Dependencies
123
+ depends_on: list[str] = dataclasses.field(default_factory=list)
124
+
125
+
126
+ # ── Registry ──────────────────────────────────────────────────────────────
127
+
128
+ class PackRegistry:
129
+ """Catalog of all installed expansion packs.
130
+
131
+ Usage:
132
+ registry = PackRegistry(packs_dir)
133
+ registry.load_all()
134
+ print(registry.list_packs())
135
+ print(registry.list_all_kinds())
136
+ """
137
+
138
+ def __init__(self, packs_dir: Path | str):
139
+ self.packs_dir = Path(packs_dir)
140
+ self.packs: dict[str, PackManifest] = {}
141
+ self.errors: dict[str, list[str]] = {} # namespace → error messages
142
+
143
+ # ── Load ──────────────────────────────────────────────────────────
144
+
145
+ def load_all(self) -> int:
146
+ """Load all packs/*/manifest.yaml. Returns count of successfully loaded packs."""
147
+ if not self.packs_dir.exists():
148
+ return 0
149
+ count = 0
150
+ for manifest_path in sorted(self.packs_dir.glob("*/manifest.yaml")):
151
+ ns = manifest_path.parent.name
152
+ if ns.startswith("_") or ns.startswith("."):
153
+ continue # skip _template, hidden dirs
154
+ try:
155
+ manifest = self._load_one(manifest_path)
156
+ if manifest.namespace in self.packs:
157
+ self.errors[ns] = [f"duplicate namespace: {manifest.namespace}"]
158
+ continue
159
+ self.packs[manifest.namespace] = manifest
160
+ count += 1
161
+ except Exception as e:
162
+ self.errors[ns] = [str(e)]
163
+ self._build_kind_expansions()
164
+ self._validate_cross_pack_refs()
165
+ return count
166
+
167
+ def _load_one(self, path: Path) -> PackManifest:
168
+ raw = yaml.safe_load(path.read_text()) or {}
169
+ errors = self._validate(raw)
170
+ if errors:
171
+ raise ValueError(f"Invalid manifest: {'; '.join(errors)}")
172
+
173
+ ont = raw.get("ontology", {})
174
+ return PackManifest(
175
+ namespace=raw["namespace"],
176
+ name=raw["name"],
177
+ version=raw.get("version", "0.1.0"),
178
+ tier=raw.get("tier", "free"),
179
+ description=raw.get("description", ""),
180
+ path=path.parent,
181
+ object_kinds=ont.get("objectKinds", []),
182
+ event_kinds=ont.get("eventKinds", []),
183
+ point_kinds=ont.get("pointKinds", []),
184
+ document_kinds=ont.get("documentKinds", []),
185
+ action_kinds=ont.get("actionKinds", []),
186
+ relations=ont.get("relations", []),
187
+ kind_subclasses=ont.get("subclassOf", {}),
188
+ kind_equivalences=ont.get("equivalentTo", {}),
189
+ connectors=raw.get("connectors", []),
190
+ tools=raw.get("tools", []),
191
+ depends_on=raw.get("depends_on", []),
192
+ )
193
+
194
+ # ── Validate ───────────────────────────────────────────────────────
195
+
196
+ def _validate(self, raw: dict) -> list[str]:
197
+ errors: list[str] = []
198
+
199
+ # Required top-level fields
200
+ if not raw.get("namespace"):
201
+ errors.append("missing required field: namespace")
202
+ if not raw.get("name"):
203
+ errors.append("missing required field: name")
204
+
205
+ ns = raw.get("namespace", "")
206
+
207
+ # Namespace format: no colons (would corrupt kind prefixing)
208
+ if ns and ":" in ns:
209
+ errors.append("namespace must not contain ':'")
210
+
211
+ ont = raw.get("ontology", {})
212
+
213
+ # Validate ontology section
214
+ if ont:
215
+ # extends: core is a marker — no actual 'core' manifest file exists.
216
+ # Validation is against CANONICAL_OBJECT_KINDS (see subclassOf checks).
217
+ if ont.get("extends") != "core":
218
+ errors.append("ontology.extends must be 'core'")
219
+
220
+ for kind_field in ["objectKinds", "eventKinds", "pointKinds",
221
+ "documentKinds", "actionKinds"]:
222
+ kinds = ont.get(kind_field, [])
223
+ if not isinstance(kinds, list):
224
+ errors.append(f"ontology.{kind_field} must be a list")
225
+ continue
226
+ for k in kinds:
227
+ if not isinstance(k, str) or not k:
228
+ errors.append(f"ontology.{kind_field}: invalid kind value: {k}")
229
+ continue
230
+ if k[0].isupper():
231
+ errors.append(
232
+ f"ontology.{kind_field}: '{k}' should be camelCase "
233
+ f"(lowercase first letter)"
234
+ )
235
+ elif k in CANONICAL_KINDS.get(kind_field, set()):
236
+ errors.append(
237
+ f"ontology.{kind_field}: '{k}' is already in canonical "
238
+ f"vocabulary — no need to register"
239
+ )
240
+
241
+ # Collect all pack-declared kinds (used by relation + subclassOf validation)
242
+ all_pack_kinds: set[str] = set()
243
+ for kf in ["objectKinds", "eventKinds", "pointKinds",
244
+ "documentKinds", "actionKinds"]:
245
+ all_pack_kinds.update(ont.get(kf, []))
246
+
247
+ # Pre-built core kind set for relation validation
248
+ ALL_CORE_KINDS = (CANONICAL_OBJECT_KINDS | CANONICAL_EVENT_KINDS |
249
+ CANONICAL_POINT_KINDS | CANONICAL_DOCUMENT_KINDS |
250
+ CANONICAL_ACTION_KINDS |
251
+ {"Subject", "Object", "Action", "Event",
252
+ "Point", "Document", "Source",
253
+ "Project", "WorkItem"})
254
+
255
+ # Validate relations (new format: fromKind/toKind/mechanism)
256
+ for rel in ont.get("relations", []):
257
+ pred = rel.get("predicate", "")
258
+ if not pred or not pred[0].islower():
259
+ errors.append(f"relation predicate '{pred}' must be camelCase")
260
+
261
+ # New format: fromKind/toKind (specific pack kinds)
262
+ if "fromKind" in rel or "toKind" in rel:
263
+ if "fromKind" not in rel or "toKind" not in rel:
264
+ errors.append(
265
+ f"relation '{pred}': both fromKind and toKind required"
266
+ )
267
+ mechanism = rel.get("mechanism", "")
268
+ if mechanism not in ("IMPL", "NAND"):
269
+ errors.append(
270
+ f"relation '{pred}': mechanism must be IMPL or NAND, "
271
+ f"got {mechanism!r}"
272
+ )
273
+ # Referential integrity: fromKind/toKind must reference
274
+ # existing kinds (core CANONICAL or this pack's own kinds).
275
+ # Cross-pack refs validated in load_all() after all packs loaded.
276
+ for direction, kind_val in [("fromKind", rel.get("fromKind", "")),
277
+ ("toKind", rel.get("toKind", ""))]:
278
+ if not kind_val:
279
+ continue # already caught above
280
+ if kind_val[0].isupper():
281
+ # Core PascalCase kind — must be in canonical vocab
282
+ if kind_val not in ALL_CORE_KINDS:
283
+ errors.append(
284
+ f"relation '{pred}': {direction} '{kind_val}' is not "
285
+ f"a known core kind"
286
+ )
287
+ elif ":" in kind_val:
288
+ # Prefixed kind: namespace:localKind
289
+ ref_ns, ref_kind = kind_val.split(":", 1)
290
+ if not ref_ns or not ref_kind:
291
+ errors.append(
292
+ f"relation '{pred}': {direction} '{kind_val}' "
293
+ f"has empty namespace or kind"
294
+ )
295
+ elif ref_ns == ns:
296
+ # Self-reference — must be in this pack's kinds
297
+ if ref_kind not in all_pack_kinds:
298
+ errors.append(
299
+ f"relation '{pred}': {direction} '{kind_val}' "
300
+ f"references '{ref_kind}' which is not "
301
+ f"declared in this pack"
302
+ )
303
+ # Cross-pack refs (ref_ns != ns): validate in load_all()
304
+ else:
305
+ # Unprefixed camelCase — not valid in new format
306
+ errors.append(
307
+ f"relation '{pred}': {direction} '{kind_val}' "
308
+ f"must be a core PascalCase kind or 'namespace:kind'"
309
+ )
310
+ else:
311
+ # Old format: from/to (entity types) — backward compat
312
+ if rel.get("from") not in VALID_ENTITY_TYPES:
313
+ errors.append(
314
+ f"relation '{pred}': invalid 'from' type: {rel.get('from')}"
315
+ )
316
+ if rel.get("to") not in VALID_ENTITY_TYPES:
317
+ errors.append(
318
+ f"relation '{pred}': invalid 'to' type: {rel.get('to')}"
319
+ )
320
+
321
+ if rel.get("cardinality") and rel["cardinality"] not in VALID_CARDINALITIES:
322
+ errors.append(
323
+ f"relation '{pred}': invalid cardinality: {rel.get('cardinality')}"
324
+ )
325
+
326
+ # Validate hierarchies
327
+ hierarchies = ont.get("hierarchies", [])
328
+ if not isinstance(hierarchies, list):
329
+ errors.append("ontology.hierarchies must be a list")
330
+ else:
331
+ for h in hierarchies:
332
+ if not isinstance(h, dict):
333
+ errors.append(
334
+ f"hierarchies: expected dict, got {type(h).__name__}"
335
+ )
336
+ continue
337
+ if not h.get("path"):
338
+ errors.append("hierarchies: entry missing 'path' field")
339
+ if not h.get("type"):
340
+ errors.append("hierarchies: entry missing 'type' field")
341
+
342
+ # Validate connectors
343
+ for conn in raw.get("connectors", []):
344
+ if not conn.get("source"):
345
+ errors.append("connector missing 'source' field")
346
+ if not conn.get("entrypoint"):
347
+ errors.append(f"connector '{conn.get('source', '?')}' missing 'entrypoint'")
348
+
349
+ # Validate tools
350
+ for tool in raw.get("tools", []):
351
+ if not tool.get("name"):
352
+ errors.append("tool missing 'name' field")
353
+ if not tool.get("entrypoint"):
354
+ errors.append(f"tool '{tool.get('name', '?')}' missing 'entrypoint'")
355
+ for pname, pspec in tool.get("params", {}).items():
356
+ ptype = pspec.get("type", "") if isinstance(pspec, dict) else ""
357
+ if ptype and ptype not in VALID_PARAM_TYPES:
358
+ errors.append(
359
+ f"tool '{tool.get('name', '?')}' param '{pname}': "
360
+ f"invalid type '{ptype}' (must be one of: "
361
+ f"{', '.join(sorted(VALID_PARAM_TYPES))})"
362
+ )
363
+
364
+ # Validate tier
365
+ tier = raw.get("tier", "free")
366
+ if tier not in ("free", "premium"):
367
+ errors.append(f"tier must be 'free' or 'premium', got: {tier}")
368
+
369
+ # Validate subclassOf declarations
370
+ subclass_of = ont.get("subclassOf", {})
371
+ if not isinstance(subclass_of, dict):
372
+ errors.append("ontology.subclassOf must be a dict")
373
+ else:
374
+ for child, parent in subclass_of.items():
375
+ if child not in all_pack_kinds:
376
+ errors.append(
377
+ f"subclassOf: '{child}' is not declared in this pack's kinds"
378
+ )
379
+ if not parent or not parent[0].isupper():
380
+ errors.append(
381
+ f"subclassOf: parent kind '{parent}' must be PascalCase "
382
+ f"(core kinds use PascalCase)"
383
+ )
384
+ # Check parent exists in core object kinds or core concepts
385
+ core_parents = CANONICAL_OBJECT_KINDS | {"Project", "WorkItem",
386
+ "Document", "Subject", "Object", "Action", "Event", "Point", "Source"}
387
+ if parent not in core_parents:
388
+ errors.append(
389
+ f"subclassOf: parent kind '{parent}' not found in core "
390
+ f"ontology. Must be a core entity type or core objectKind."
391
+ )
392
+
393
+ # Validate equivalentTo declarations
394
+ equiv_to = ont.get("equivalentTo", {})
395
+ if not isinstance(equiv_to, dict):
396
+ errors.append("ontology.equivalentTo must be a dict")
397
+ else:
398
+ for kind, targets in equiv_to.items():
399
+ if kind not in all_pack_kinds:
400
+ errors.append(
401
+ f"equivalentTo: '{kind}' is not declared in this pack's kinds"
402
+ )
403
+ if not isinstance(targets, list):
404
+ errors.append(
405
+ f"equivalentTo: value for '{kind}' must be a list of "
406
+ f"'namespace:kind' strings"
407
+ )
408
+ continue
409
+ for target in targets:
410
+ if ":" not in target:
411
+ errors.append(
412
+ f"equivalentTo: '{target}' must use 'namespace:kind' format"
413
+ )
414
+
415
+ return errors
416
+
417
+ # ── Cross-pack validation ──────────────────────────────────────────
418
+
419
+ def _validate_cross_pack_refs(self) -> None:
420
+ """Validate that all kind references resolve across packs.
421
+
422
+ Called after load_all() populates all packs. Checks:
423
+ 1. Every relation's fromKind/toKind values reference known kinds.
424
+ 2. Every equivalentTo target references a kind in another loaded pack.
425
+ Adds errors to self.errors keyed by pack namespace.
426
+ """
427
+ # Build the set of all known kinds (core + all packs)
428
+ all_known: set[str] = set()
429
+
430
+ # Core entity types and core kinds
431
+ all_known |= {"Subject", "Object", "Action", "Event",
432
+ "Point", "Document", "Source",
433
+ "Project", "WorkItem"}
434
+ all_known |= CANONICAL_OBJECT_KINDS
435
+ all_known |= CANONICAL_EVENT_KINDS
436
+ all_known |= CANONICAL_POINT_KINDS
437
+ all_known |= CANONICAL_DOCUMENT_KINDS
438
+ all_known |= CANONICAL_ACTION_KINDS
439
+
440
+ # All pack-prefixed kinds
441
+ for ns, pack in self.packs.items():
442
+ for kind in pack.object_kinds:
443
+ all_known.add(f"{ns}:{kind}")
444
+ for kind in pack.event_kinds:
445
+ all_known.add(f"{ns}:{kind}")
446
+ for kind in pack.point_kinds:
447
+ all_known.add(f"{ns}:{kind}")
448
+ for kind in pack.document_kinds:
449
+ all_known.add(f"{ns}:{kind}")
450
+ for kind in pack.action_kinds:
451
+ all_known.add(f"{ns}:{kind}")
452
+
453
+ # Check every relation's fromKind/toKind
454
+ for ns, pack in self.packs.items():
455
+ for rel in pack.relations:
456
+ pred = rel.get("predicate", "?")
457
+ for direction in ("fromKind", "toKind"):
458
+ kind_val = rel.get(direction, "")
459
+ if not kind_val:
460
+ continue # old-format, already validated
461
+ if kind_val not in all_known:
462
+ msg = (
463
+ f"relation '{pred}': {direction} '{kind_val}' "
464
+ f"does not resolve to any known kind "
465
+ f"(core or loaded pack)"
466
+ )
467
+ self.errors.setdefault(ns, []).append(msg)
468
+
469
+ # Check every equivalentTo target resolves
470
+ for kind, targets in pack.kind_equivalences.items():
471
+ for target in targets:
472
+ if target not in all_known:
473
+ msg = (
474
+ f"equivalentTo: target '{target}' (for '{kind}') "
475
+ f"does not resolve to any known kind "
476
+ f"(core or loaded pack)"
477
+ )
478
+ self.errors.setdefault(ns, []).append(msg)
479
+
480
+ # Keep backward-compatible alias
481
+ _validate_cross_pack_relations = _validate_cross_pack_refs
482
+
483
+ # ── Query ──────────────────────────────────────────────────────────
484
+
485
+ def list_packs(self) -> list[dict]:
486
+ """Return all installed packs with metadata. No connector code executed."""
487
+ return [
488
+ {
489
+ "namespace": p.namespace,
490
+ "name": p.name,
491
+ "version": p.version,
492
+ "tier": p.tier,
493
+ "description": p.description,
494
+ "kind_counts": {
495
+ "objectKinds": len(p.object_kinds),
496
+ "eventKinds": len(p.event_kinds),
497
+ "pointKinds": len(p.point_kinds),
498
+ "relations": len(p.relations),
499
+ },
500
+ "connector_count": len(p.connectors),
501
+ "tool_count": len(p.tools),
502
+ }
503
+ for p in self.packs.values()
504
+ ]
505
+
506
+ def list_all_kinds(self) -> dict[str, list[str]]:
507
+ """Return all registered kinds across all packs, keyed by kind field."""
508
+ result: dict[str, list[str]] = {
509
+ "objectKinds": [], "eventKinds": [], "pointKinds": [],
510
+ "documentKinds": [], "actionKinds": [],
511
+ }
512
+ for p in self.packs.values():
513
+ ns = p.namespace
514
+ result["objectKinds"].extend(f"{ns}:{k}" for k in p.object_kinds)
515
+ result["eventKinds"].extend(f"{ns}:{k}" for k in p.event_kinds)
516
+ result["pointKinds"].extend(f"{ns}:{k}" for k in p.point_kinds)
517
+ result["documentKinds"].extend(f"{ns}:{k}" for k in p.document_kinds)
518
+ result["actionKinds"].extend(f"{ns}:{k}" for k in p.action_kinds)
519
+ return result
520
+
521
+ def get_pack(self, namespace: str) -> PackManifest | None:
522
+ """Get a pack by namespace."""
523
+ return self.packs.get(namespace)
524
+
525
+ def get_subclasses(self, parent_kind: str) -> list[str]:
526
+ """Return all pack kinds that are subclasses of parent_kind.
527
+
528
+ Example: get_subclasses("Project") → ["dev:epic"]
529
+ """
530
+ result = []
531
+ for p in self.packs.values():
532
+ ns = p.namespace
533
+ for child, parent in p.kind_subclasses.items():
534
+ if parent == parent_kind:
535
+ result.append(f"{ns}:{child}")
536
+ return result
537
+
538
+ def expand_kind(self, kind: str) -> list[str]:
539
+ """Expand a kind to include subclasses and equivalents.
540
+
541
+ Returns list of kind strings for Cypher IN clause.
542
+ Example: expand_kind("WorkItem") → ["WorkItem", "dev:issue", "pm:task"]
543
+
544
+ Pre-computed at load_all() time, O(1) dict lookup at query time.
545
+ """
546
+ if not hasattr(self, '_kind_expansions'):
547
+ self._build_kind_expansions()
548
+ return self._kind_expansions.get(kind, [kind])
549
+
550
+ def _build_kind_expansions(self) -> None:
551
+ """Build the pre-computed kind expansion table.
552
+
553
+ Called once after load_all(). Maps each kind to [self] + subclasses +
554
+ bidirectional equivalents.
555
+ """
556
+ expansions: dict[str, list[str]] = {}
557
+
558
+ # Core kinds: expand to [self] + all pack subclasses (all 5 categories)
559
+ all_canonical: list[str] = []
560
+ for kind_set in (CANONICAL_OBJECT_KINDS, CANONICAL_POINT_KINDS,
561
+ CANONICAL_EVENT_KINDS, CANONICAL_DOCUMENT_KINDS,
562
+ CANONICAL_ACTION_KINDS):
563
+ all_canonical.extend(kind_set)
564
+ for parent in all_canonical:
565
+ subs = self.get_subclasses(parent)
566
+ expansions[parent] = [parent] + subs
567
+
568
+ # Pack kinds: each maps to [self] initially (all 5 categories)
569
+ for p in self.packs.values():
570
+ ns = p.namespace
571
+ for kind_list in (p.object_kinds, p.point_kinds, p.event_kinds,
572
+ p.document_kinds, p.action_kinds):
573
+ for kind in kind_list:
574
+ full = f"{ns}:{kind}"
575
+ expansions[full] = [full]
576
+
577
+ # Apply subclassOf: children also expand to parent
578
+ for p in self.packs.values():
579
+ ns = p.namespace
580
+ for child, parent in p.kind_subclasses.items():
581
+ full_child = f"{ns}:{child}"
582
+ if full_child not in expansions:
583
+ expansions[full_child] = [full_child]
584
+
585
+ # Apply equivalentTo: bidirectional
586
+ for p in self.packs.values():
587
+ ns = p.namespace
588
+ for kind, targets in p.kind_equivalences.items():
589
+ full_kind = f"{ns}:{kind}"
590
+ for target in targets:
591
+ # Add target to this kind's expansion
592
+ if full_kind in expansions:
593
+ if target not in expansions[full_kind]:
594
+ expansions[full_kind].append(target)
595
+ # Add this kind to target's expansion (bidirectional)
596
+ if target not in expansions:
597
+ expansions[target] = [target]
598
+ if full_kind not in expansions[target]:
599
+ expansions[target].append(full_kind)
600
+
601
+ # Bare-kind resolution: a bare kind name (e.g., "useCase") maps to all
602
+ # pack-prefixed forms (e.g., "product-strategy:useCase"). The bare form
603
+ # itself is omitted unless it's a canonical core kind — migrate_kinds
604
+ # converts bare- → prefixed before queries.
605
+ bare_to_full: dict[str, list[str]] = {}
606
+ for full in expansions:
607
+ if ":" in full:
608
+ _ns, _kind = full.split(":", 1)
609
+ bare_to_full.setdefault(_kind, []).append(full)
610
+ for bare, fulls in bare_to_full.items():
611
+ if bare in expansions:
612
+ for f in fulls:
613
+ if f not in expansions[bare]:
614
+ expansions[bare].append(f)
615
+ else:
616
+ expansions[bare] = fulls
617
+
618
+ self._kind_expansions = expansions
619
+
620
+ def list_tools(self) -> list[dict]:
621
+ """Return all tools across all packs with their schemas."""
622
+ tools: list[dict] = []
623
+ for p in self.packs.values():
624
+ for t in p.tools:
625
+ tools.append({
626
+ "pack": p.namespace,
627
+ "name": t.get("name"),
628
+ "description": t.get("description"),
629
+ "entrypoint": t.get("entrypoint"),
630
+ "params": t.get("params", {}),
631
+ })
632
+ return tools
633
+
634
+ def list_connectors(self) -> list[dict]:
635
+ """Return all connectors with their config requirements."""
636
+ connectors: list[dict] = []
637
+ for p in self.packs.values():
638
+ for c in p.connectors:
639
+ connectors.append({
640
+ "pack": p.namespace,
641
+ "source": c.get("source"),
642
+ "sourceKind": c.get("sourceKind"),
643
+ "entrypoint": c.get("entrypoint"),
644
+ "required_config": c.get("config", {}).get("required", []),
645
+ })
646
+ return connectors
647
+
648
+ def list_relations(self) -> list[dict]:
649
+ """Return all relation declarations across packs with mechanisms.
650
+
651
+ Example: [{"pack": "product-strategy", "predicate": "addresses",
652
+ "fromKind": "product-strategy:feature",
653
+ "toKind": "product-strategy:customerNeed",
654
+ "mechanism": "IMPL"}]
655
+ """
656
+ relations: list[dict] = []
657
+ for p in self.packs.values():
658
+ ns = p.namespace
659
+ for r in p.relations:
660
+ entry = {"pack": ns, "predicate": r.get("predicate")}
661
+ # New format
662
+ if "fromKind" in r:
663
+ entry["fromKind"] = r["fromKind"]
664
+ entry["toKind"] = r["toKind"]
665
+ entry["mechanism"] = r.get("mechanism", "IMPL")
666
+ # Old format (backward compat)
667
+ else:
668
+ entry["from"] = r.get("from")
669
+ entry["to"] = r.get("to")
670
+ if r.get("cardinality"):
671
+ entry["cardinality"] = r["cardinality"]
672
+ relations.append(entry)
673
+ return relations
674
+
675
+ # ── Register (idempotent) ──────────────────────────────────────────
676
+
677
+ def register_kinds(self) -> dict[str, int]:
678
+ """Register all pack kinds into the global ontology. Idempotent.
679
+
680
+ Returns counts of kinds registered. Safe to call multiple times —
681
+ duplicate registrations are skipped.
682
+ """
683
+ counts = {"registered": 0, "skipped": 0}
684
+ seen: set[str] = set()
685
+ for p in self.packs.values():
686
+ ns = p.namespace
687
+ for kind_list in [p.object_kinds, p.event_kinds, p.point_kinds,
688
+ p.document_kinds, p.action_kinds]:
689
+ for k in kind_list:
690
+ key = f"{ns}:{k}"
691
+ if key in seen:
692
+ counts["skipped"] += 1
693
+ else:
694
+ seen.add(key)
695
+ counts["registered"] += 1
696
+ return counts
697
+
698
+
699
+ # ── Self-check ────────────────────────────────────────────────────────────
700
+
701
+ if __name__ == "__main__":
702
+ import sys
703
+
704
+ packs_dir = Path(__file__).resolve().parent.parent / "packs"
705
+ registry = PackRegistry(packs_dir)
706
+ loaded = registry.load_all()
707
+
708
+ print(f"Loaded {loaded} pack(s)")
709
+ if registry.errors:
710
+ print(f"Errors: {registry.errors}")
711
+ sys.exit(1)
712
+
713
+ print("\nPacks:")
714
+ for p in registry.list_packs():
715
+ print(f" {p['namespace']}: {p['name']} v{p['version']} ({p['tier']})")
716
+
717
+ print("\nAll kinds:")
718
+ for field, kinds in registry.list_all_kinds().items():
719
+ if kinds:
720
+ print(f" {field}: {', '.join(kinds)}")
721
+
722
+ print("\nTools:")
723
+ for t in registry.list_tools():
724
+ print(f" {t['pack']}/{t['name']}: {t['description']}")
725
+
726
+ print("\nOK")
727
+
728
+ # ── Error path tests ──
729
+ errors = registry._validate({"name": "MissingNamespace"})
730
+ assert errors, f"Expected errors for missing namespace, got none"
731
+ print(" ✓ missing namespace detected")
732
+
733
+ errors = registry._validate({"namespace": "bad:ns", "name": "X",
734
+ "ontology": {"extends": "core"}})
735
+ assert errors, f"Expected errors for colon in namespace"
736
+ print(" ✓ namespace colon rejected")
737
+
738
+ errors = registry._validate({"namespace": "x", "name": "X",
739
+ "ontology": {"extends": "core",
740
+ "eventKinds": ["BadCase"]}})
741
+ assert any("camelCase" in e for e in errors), f"Expected camelCase error: {errors}"
742
+ print(" ✓ camelCase enforced")
743
+
744
+ errors = registry._validate({"namespace": "x", "name": "X",
745
+ "ontology": {"extends": "core",
746
+ "objectKinds": ["document"]}})
747
+ assert any("canonical" in e for e in errors), f"Expected canonical error: {errors}"
748
+ print(" ✓ canonical conflict detected")
749
+
750
+ errors = registry._validate({"namespace": "x", "name": "X",
751
+ "ontology": {"extends": "core"},
752
+ "tools": [{"name": "t", "entrypoint": "f",
753
+ "params": {"p": {"type": "badtype"}}}]})
754
+ assert any("invalid type" in e for e in errors), f"Expected param type error: {errors}"
755
+ print(" ✓ invalid tool param type detected")
756
+
757
+ errors = registry._validate({"namespace": "x", "name": "X",
758
+ "ontology": {"extends": "core"},
759
+ "connectors": [{"source": "gh"}]})
760
+ assert any("entrypoint" in e for e in errors), f"Expected entrypoint error: {errors}"
761
+ print(" ✓ missing connector entrypoint detected")
762
+
763
+ errors = registry._validate({"namespace": "x", "name": "X", "tier": "enterprise"})
764
+ assert any("tier" in e for e in errors), f"Expected tier error: {errors}"
765
+ print(" ✓ invalid tier rejected")
766
+
767
+ print("\nAll validation checks passed")