ioc-scope-api 1.0.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 (106) hide show
  1. ioc_scope_api-1.0.0.dist-info/METADATA +306 -0
  2. ioc_scope_api-1.0.0.dist-info/RECORD +106 -0
  3. ioc_scope_api-1.0.0.dist-info/WHEEL +4 -0
  4. ioc_scope_api-1.0.0.dist-info/entry_points.txt +2 -0
  5. scope/__init__.py +27 -0
  6. scope/api/__init__.py +119 -0
  7. scope/api/api_v1/__init__.py +2 -0
  8. scope/api/api_v1/api.py +71 -0
  9. scope/api/api_v1/endpoints/__init__.py +2 -0
  10. scope/api/api_v1/endpoints/agentic_protocols_metrics.py +39 -0
  11. scope/api/api_v1/endpoints/applications.py +440 -0
  12. scope/api/api_v1/endpoints/cache.py +50 -0
  13. scope/api/api_v1/endpoints/concepts.py +123 -0
  14. scope/api/api_v1/endpoints/features.py +19 -0
  15. scope/api/api_v1/endpoints/helpers.py +65 -0
  16. scope/api/api_v1/endpoints/kg.py +195 -0
  17. scope/api/api_v1/endpoints/labels.py +71 -0
  18. scope/api/api_v1/endpoints/live_topology.py +89 -0
  19. scope/api/api_v1/endpoints/metrics.py +1014 -0
  20. scope/api/api_v1/endpoints/reasoning.py +62 -0
  21. scope/api/api_v1/endpoints/semanticgroups.py +144 -0
  22. scope/api/api_v1/endpoints/sessions.py +339 -0
  23. scope/api/api_v1/endpoints/spans.py +41 -0
  24. scope/api/api_v1/endpoints/symbolic.py +186 -0
  25. scope/api/api_v1/endpoints/ui.py +145 -0
  26. scope/api/api_v1/endpoints/waste_estimation.py +182 -0
  27. scope/api/api_v2/__init__.py +3 -0
  28. scope/api/api_v2/api.py +23 -0
  29. scope/api/api_v2/endpoints/__init__.py +3 -0
  30. scope/api/api_v2/endpoints/metrics.py +193 -0
  31. scope/app.py +30 -0
  32. scope/cache.py +64 -0
  33. scope/client/__init__.py +27 -0
  34. scope/client/_concepts.py +137 -0
  35. scope/client/_kg.py +64 -0
  36. scope/client/_labels.py +86 -0
  37. scope/client/_live_topology.py +912 -0
  38. scope/client/_metrics.py +561 -0
  39. scope/client/_semanticgroups.py +166 -0
  40. scope/client/_sessions.py +168 -0
  41. scope/client/_symbolic.py +1354 -0
  42. scope/client/_ui.py +599 -0
  43. scope/client/agentic_protocols.py +289 -0
  44. scope/client/application_charts.py +1786 -0
  45. scope/client/applications.py +2246 -0
  46. scope/client/base.py +49 -0
  47. scope/client/cognition_protocols.py +302 -0
  48. scope/client/constants.py +81 -0
  49. scope/client/dal.py +2382 -0
  50. scope/client/failures.py +70 -0
  51. scope/client/local.py +161 -0
  52. scope/client/mock/__init__.py +7 -0
  53. scope/client/mock/client.py +1034 -0
  54. scope/client/sessions.py +1688 -0
  55. scope/client/spans.py +95 -0
  56. scope/client/utils.py +392 -0
  57. scope/connectors/__init__.py +13 -0
  58. scope/connectors/base.py +52 -0
  59. scope/connectors/clickhouse.py +105 -0
  60. scope/connectors/neo4j.py +220 -0
  61. scope/connectors/sqlalchemy.py +131 -0
  62. scope/core/config.py +530 -0
  63. scope/core/exceptions.py +64 -0
  64. scope/dependencies.py +164 -0
  65. scope/health.py +10 -0
  66. scope/interfaces/__init__.py +33 -0
  67. scope/interfaces/data_provider.py +61 -0
  68. scope/interfaces/integration_example.py +310 -0
  69. scope/interfaces/kg_provider.py +91 -0
  70. scope/interfaces/metrics_provider.py +92 -0
  71. scope/interfaces/models.py +185 -0
  72. scope/models/kg.py +48 -0
  73. scope/models/live_topology.py +78 -0
  74. scope/models/otel_traces.py +1595 -0
  75. scope/providers/__init__.py +277 -0
  76. scope/providers/_graph.py +59 -0
  77. scope/providers/cognition_protocols.py +178 -0
  78. scope/providers/kg.py +702 -0
  79. scope/providers/kg_query_runner.py +109 -0
  80. scope/providers/neo4j_mce.py +18 -0
  81. scope/providers/scope_metrics.py +7 -0
  82. scope/query_builders/__init__.py +14 -0
  83. scope/query_builders/cognition_protocol_graph.py +191 -0
  84. scope/query_builders/concepts.py +112 -0
  85. scope/query_builders/dal.py +931 -0
  86. scope/query_builders/failure_graph.py +102 -0
  87. scope/query_builders/features.py +5 -0
  88. scope/query_builders/kg.py +416 -0
  89. scope/query_builders/labels.py +53 -0
  90. scope/query_builders/live_topology.py +503 -0
  91. scope/query_builders/metric_graph.py +196 -0
  92. scope/query_builders/metrics.py +354 -0
  93. scope/query_builders/semanticgroups.py +46 -0
  94. scope/query_builders/sessions.py +208 -0
  95. scope/query_builders/symbolic.py +615 -0
  96. scope/query_builders/trajectory.py +76 -0
  97. scope/query_builders/types.py +20 -0
  98. scope/query_builders/ui.py +3278 -0
  99. scope/query_builders/waste_estimation.py +221 -0
  100. scope/repositories/__init__.py +28 -0
  101. scope/repositories/clickhouse_otel_repository.py +135 -0
  102. scope/repositories/otel_repository.py +97 -0
  103. scope/repositories/sqlite_repository.py +215 -0
  104. scope/scripts/__init__.py +2 -0
  105. scope/scripts/seed.py +35 -0
  106. scope/workarounds.py +38 -0
@@ -0,0 +1,109 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query execution helpers for ontology/workaround KG reads."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import logging
8
+ from typing import Any, Callable
9
+
10
+ from scope.connectors.base import Connector
11
+ from scope.query_builders.types import QueryPair
12
+ from scope.workarounds import KGWorkaroundsConfig
13
+
14
+ KGRow = dict[str, Any]
15
+ HasResults = Callable[[list[KGRow]], bool]
16
+
17
+
18
+ class KGQueryExecutionError(RuntimeError):
19
+ """Raised when ontology and workaround KG queries both fail to execute."""
20
+
21
+ def __init__(
22
+ self,
23
+ ctx: str,
24
+ primary_error: Exception | None,
25
+ fallback_error: Exception | None,
26
+ ) -> None:
27
+ details: list[str] = []
28
+ if primary_error is not None:
29
+ details.append(f"primary={primary_error}")
30
+ if fallback_error is not None:
31
+ details.append(f"fallback={fallback_error}")
32
+ suffix = f": {', '.join(details)}" if details else ""
33
+ super().__init__(
34
+ f"KG query execution failed for {ctx or 'unknown context'}{suffix}"
35
+ )
36
+ self.ctx = ctx
37
+ self.primary_error = primary_error
38
+ self.fallback_error = fallback_error
39
+
40
+
41
+ class KGQueryRunner:
42
+ """Execute KG queries with explicit ontology/workaround fallback."""
43
+
44
+ def __init__(
45
+ self,
46
+ db: Connector,
47
+ workarounds: KGWorkaroundsConfig,
48
+ *,
49
+ logger: logging.Logger | None = None,
50
+ ) -> None:
51
+ self._db = db
52
+ self._workarounds = workarounds
53
+ self._logger = logger or logging.getLogger(__name__)
54
+
55
+ def execute(self, query: str, params: dict[str, Any] | None = None) -> list[KGRow]:
56
+ """Execute a single KG query and normalize empty results."""
57
+ rows = self._db.execute(query, params or {})
58
+ return rows or []
59
+
60
+ def execute_pair(
61
+ self,
62
+ ontology: QueryPair,
63
+ workaround: QueryPair,
64
+ *,
65
+ has_results: HasResults | None = None,
66
+ ctx: str = "",
67
+ ) -> list[KGRow]:
68
+ """Execute a query pair according to the configured workaround policy."""
69
+ predicate = has_results or bool
70
+ if self._workarounds.workarounds_first:
71
+ primary, primary_label = workaround, "workaround"
72
+ fallback, fallback_label = ontology, "ontology"
73
+ else:
74
+ primary, primary_label = ontology, "ontology"
75
+ fallback, fallback_label = workaround, "workaround"
76
+
77
+ primary_error: Exception | None = None
78
+
79
+ try:
80
+ rows = self.execute(*primary)
81
+ if predicate(rows):
82
+ self._logger.debug("[%s] %s query succeeded", ctx, primary_label)
83
+ return rows
84
+ self._logger.debug(
85
+ "[%s] %s query returned empty, trying %s",
86
+ ctx,
87
+ primary_label,
88
+ fallback_label,
89
+ )
90
+ except Exception as exc:
91
+ self._logger.debug(
92
+ "[%s] %s query raised: %s — trying %s",
93
+ ctx,
94
+ primary_label,
95
+ exc,
96
+ fallback_label,
97
+ )
98
+ primary_error = exc
99
+
100
+ try:
101
+ return self.execute(*fallback)
102
+ except Exception as exc:
103
+ self._logger.warning(
104
+ "[%s] %s fallback also failed: %s",
105
+ ctx,
106
+ fallback_label,
107
+ exc,
108
+ )
109
+ raise KGQueryExecutionError(ctx, primary_error, exc) from exc
@@ -0,0 +1,18 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """neo4j_mce — backward-compat re-export.
4
+
5
+ ``Neo4jMCEProvider`` has been merged into ``SCOPEMetricsProvider``
6
+ (``scope.providers``), which now implements all three canonical interfaces:
7
+ ``MetricsProvider``, ``DataProvider``, and ``KGProvider``.
8
+
9
+ This module is kept exclusively so that existing imports of the form::
10
+
11
+ from scope.providers.neo4j_mce import Neo4jMCEProvider
12
+
13
+ continue to work without modification. Do not add new code here.
14
+ """
15
+
16
+ from scope.providers import SCOPEMetricsProvider as Neo4jMCEProvider # noqa: F401
17
+
18
+ __all__ = ["Neo4jMCEProvider"]
@@ -0,0 +1,7 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Concrete :class:`MetricsProvider` backed by the existing SCOPE connector + query builders."""
4
+
5
+ from scope.providers import SCOPEMetricsProvider
6
+
7
+ __all__ = ["SCOPEMetricsProvider"]
@@ -0,0 +1,14 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """SCOPE query builders — one module per feature domain.
4
+
5
+ Example::
6
+
7
+ from scope.query_builders import ui
8
+
9
+ stmt = ui.sessions_query(app_name="my-app")
10
+ """
11
+
12
+ from scope.query_builders.types import Dialect, QueryAndParams
13
+
14
+ __all__ = ["Dialect", "QueryAndParams"]
@@ -0,0 +1,191 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """How Cognition protocol reports are stored in the knowledge graph.
4
+
5
+ ::
6
+
7
+ (r:CognitionProtocolReport {id, sessionId, protocolsEnabled, protocolsActivated, reportedAt})
8
+ -[:reportsOn]-> (s:Session)
9
+ (p:CognitionProtocolExecutionReport {id, sessionId, protocol, enabledEvidence, skillsEnabled,
10
+ skillsActivated, agentsEnabled, agentsActivated,
11
+ metricCount, reportedAt})
12
+ -[:reportsOn]-> (s:Session)
13
+ (m:MetricResult) -[:measures]-> (p:CognitionProtocolExecutionReport)
14
+
15
+ An ``CognitionProtocolReport`` says which Cognition protocols were enabled and which activated in a
16
+ session: lists of protocol names, so a new protocol adds an entry, not a
17
+ property. An ``CognitionProtocolExecutionReport`` is everything about one protocol in
18
+ one session: who had it, who used it, and its evaluation metrics (see
19
+ ``metric_graph``, which writes the ``MetricResult`` nodes that measure it).
20
+
21
+ Both are keyed by session (and protocol), so writing again overwrites. The node
22
+ properties are exactly the fields of the models generated from the ontology
23
+ (``scope_ontology.models.nodes.CognitionProtocolReport`` / ``CognitionProtocolExecutionReport``); every
24
+ write is validated against them. Different writers fill different properties of
25
+ the same protocol report (who took part, the metrics), so each builder returns
26
+ only the properties its writer owns and the others are left as they are.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import hashlib
32
+ from collections.abc import Iterable
33
+ from datetime import UTC, datetime
34
+ from typing import Any
35
+
36
+ from scope_ontology.models.nodes import (
37
+ CognitionProtocolExecutionReport as ProtocolReportModel,
38
+ )
39
+ from scope_ontology.models.nodes import (
40
+ CognitionProtocolReport as CognitionProtocolReportModel,
41
+ )
42
+
43
+ QueryPair = tuple[str, dict[str, Any]]
44
+
45
+ COGNITION_PROTOCOL_REPORT = "CognitionProtocolReport"
46
+ COGNITION_PROTOCOL_EXECUTION_REPORT = "CognitionProtocolExecutionReport"
47
+
48
+ _PARTICIPATION_FIELDS = {
49
+ "id",
50
+ "name",
51
+ "sessionId",
52
+ "protocol",
53
+ "enabledEvidence",
54
+ "skillsEnabled",
55
+ "skillsActivated",
56
+ "agentsEnabled",
57
+ "agentsActivated",
58
+ "reportedAt",
59
+ }
60
+ _METRICS_FIELDS = {"id", "name", "sessionId", "protocol", "metricCount", "reportedAt"}
61
+
62
+
63
+ def _digest(*parts: str) -> str:
64
+ return hashlib.sha1("\x1f".join(parts).encode("utf-8")).hexdigest()[:12]
65
+
66
+
67
+ def cognition_protocol_report_id(session_id: str) -> str:
68
+ """Id of the ``CognitionProtocolReport`` of a session."""
69
+ return f"cognitionprotocolreport:{_digest(session_id)}"
70
+
71
+
72
+ def protocol_execution_report_id(session_id: str, protocol: str) -> str:
73
+ """Id of the ``CognitionProtocolExecutionReport`` of a protocol in a session."""
74
+ return f"cognitionprotocolexecutionreport:{_digest(protocol, session_id)}"
75
+
76
+
77
+ def _names(values: Iterable[str]) -> list[str]:
78
+ return sorted({str(v) for v in values})
79
+
80
+
81
+ def cognition_protocol_report_properties(
82
+ session_id: str,
83
+ protocols_enabled: Iterable[str],
84
+ protocols_activated: Iterable[str],
85
+ reported_at: datetime | None = None,
86
+ ) -> dict[str, Any]:
87
+ """Properties of the ontology ``CognitionProtocolReport`` (validated against the model)."""
88
+ return CognitionProtocolReportModel(
89
+ id=cognition_protocol_report_id(session_id),
90
+ name="Cognition protocol report",
91
+ sessionId=session_id,
92
+ protocolsEnabled=_names(protocols_enabled),
93
+ protocolsActivated=_names(protocols_activated),
94
+ reportedAt=reported_at or datetime.now(UTC),
95
+ ).model_dump()
96
+
97
+
98
+ def protocol_participation_properties(
99
+ session_id: str,
100
+ protocol: str,
101
+ *,
102
+ enabled_evidence: str = "",
103
+ skills_enabled: Iterable[str] = (),
104
+ skills_activated: Iterable[str] = (),
105
+ agents_enabled: Iterable[str] = (),
106
+ agents_activated: Iterable[str] = (),
107
+ reported_at: datetime | None = None,
108
+ ) -> dict[str, Any]:
109
+ """Who had a protocol and who used it: the participation properties of its execution report."""
110
+ model = ProtocolReportModel(
111
+ id=protocol_execution_report_id(session_id, protocol),
112
+ name=protocol,
113
+ sessionId=session_id,
114
+ protocol=protocol,
115
+ enabledEvidence=enabled_evidence,
116
+ skillsEnabled=_names(skills_enabled),
117
+ skillsActivated=_names(skills_activated),
118
+ agentsEnabled=_names(agents_enabled),
119
+ agentsActivated=_names(agents_activated),
120
+ reportedAt=reported_at or datetime.now(UTC),
121
+ )
122
+ return model.model_dump(include=_PARTICIPATION_FIELDS)
123
+
124
+
125
+ def protocol_metrics_properties(
126
+ session_id: str,
127
+ protocol: str,
128
+ metric_count: int,
129
+ reported_at: datetime | None = None,
130
+ ) -> dict[str, Any]:
131
+ """The metrics-side properties of an execution report: its identity and how many metrics it has."""
132
+ model = ProtocolReportModel(
133
+ id=protocol_execution_report_id(session_id, protocol),
134
+ name=protocol,
135
+ sessionId=session_id,
136
+ protocol=protocol,
137
+ metricCount=metric_count,
138
+ reportedAt=reported_at or datetime.now(UTC),
139
+ )
140
+ return model.model_dump(include=_METRICS_FIELDS)
141
+
142
+
143
+ def session_exists_query(session_id: str) -> QueryPair:
144
+ """One row (``sessionId``) if the session is in the graph, none otherwise."""
145
+ return (
146
+ "MATCH (s:Session {sessionId: $session_id}) RETURN s.sessionId AS sessionId LIMIT 1",
147
+ {"session_id": session_id},
148
+ )
149
+
150
+
151
+ def write_cognition_protocol_report_query(
152
+ session_id: str, props: dict[str, Any]
153
+ ) -> QueryPair:
154
+ """MERGE the session's ``CognitionProtocolReport`` and link it to the session. Nothing is written if the session is missing."""
155
+ query = f"""
156
+ MATCH (s:Session {{sessionId: $session_id}})
157
+ MERGE (r:{COGNITION_PROTOCOL_REPORT} {{id: $props.id}})
158
+ SET r += $props
159
+ MERGE (r)-[:reportsOn]->(s)
160
+ RETURN r.id AS id
161
+ """
162
+ return query, {"session_id": session_id, "props": props}
163
+
164
+
165
+ def write_protocol_execution_report_query(
166
+ session_id: str, props: dict[str, Any]
167
+ ) -> QueryPair:
168
+ """MERGE a protocol's execution report and link it to the session.
169
+
170
+ ``props`` holds only the properties the caller owns (see ``protocol_participation_properties``
171
+ and ``protocol_metrics_properties``): the others stay as they are. Nothing is written if the
172
+ session is missing.
173
+ """
174
+ query = f"""
175
+ MATCH (s:Session {{sessionId: $session_id}})
176
+ MERGE (p:{COGNITION_PROTOCOL_EXECUTION_REPORT} {{id: $props.id}})
177
+ SET p += $props
178
+ MERGE (p)-[:reportsOn]->(s)
179
+ RETURN p.id AS id
180
+ """
181
+ return query, {"session_id": session_id, "props": props}
182
+
183
+
184
+ def clear_protocol_execution_report_metrics_query(report_id: str) -> QueryPair:
185
+ """Delete the metric results measuring a protocol execution report (the ``Metric`` definitions stay)."""
186
+ query = f"""
187
+ MATCH (r:MetricResult)-[:measures]->(p:{COGNITION_PROTOCOL_EXECUTION_REPORT} {{id: $report_id}})
188
+ DETACH DELETE r
189
+ RETURN count(r) AS deleted
190
+ """
191
+ return query, {"report_id": report_id}
@@ -0,0 +1,112 @@
1
+ # Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Query builders for the **Concepts** feature domain.
4
+
5
+ Provides Cypher query builders for retrieving neurosymbolic concepts
6
+ (symbols) from the knowledge graph, scoped by application and optionally
7
+ by session + span.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+
15
+ def app_concepts_query(
16
+ app_id: str,
17
+ ) -> tuple[str, dict[str, Any]]:
18
+ """Return all concepts / symbols for a given application.
19
+
20
+ The graph model is expected to have ``(:Application)-[:hasConcept]->(:Concept)``
21
+ edges. Each ``Concept`` node carries ``name``, ``type`` and arbitrary
22
+ extra properties.
23
+ """
24
+ query = """
25
+ MATCH (app:Application {applicationId: $app_id})-[:hasConcept]->(c:Concept)
26
+ RETURN
27
+ c.name AS name,
28
+ c.type AS type,
29
+ properties(c) AS properties
30
+ ORDER BY c.name
31
+ """
32
+ return query, {"app_id": app_id}
33
+
34
+
35
+ def span_concepts_query(
36
+ app_id: str,
37
+ session_id: str,
38
+ span_id: str,
39
+ ) -> tuple[str, dict[str, Any]]:
40
+ """Return concepts / symbols attached to a specific span.
41
+
42
+ Traversal: ``Application -> Session -> Span -> Concept``.
43
+ """
44
+ query = """
45
+ MATCH (app:Application {applicationId: $app_id})
46
+ -[:hasSession]->(session:Session {sessionId: $session_id})
47
+ -[:hasSpan]->(span:Span {spanId: $span_id})
48
+ -[:hasConcept]->(c:Concept)
49
+ RETURN
50
+ c.name AS name,
51
+ c.type AS type,
52
+ properties(c) AS properties
53
+ ORDER BY c.name
54
+ """
55
+ return query, {
56
+ "app_id": app_id,
57
+ "session_id": session_id,
58
+ "span_id": span_id,
59
+ }
60
+
61
+
62
+ # ── write queries ─────────────────────────────────────────────────────────────
63
+
64
+
65
+ def write_app_concept_query(
66
+ app_id: str,
67
+ name: str,
68
+ concept_type: str = "",
69
+ properties: dict | None = None,
70
+ ) -> tuple[str, dict[str, Any]]:
71
+ """Build a MERGE query to attach a concept to an application node."""
72
+ query = """
73
+ MERGE (app:Application {applicationId: $app_id})
74
+ MERGE (app)-[:hasConcept]->(c:Concept {name: $name})
75
+ SET c.type = $concept_type
76
+ SET c += $properties
77
+ RETURN c.name AS name
78
+ """
79
+ return query, {
80
+ "app_id": app_id,
81
+ "name": name,
82
+ "concept_type": concept_type,
83
+ "properties": properties or {},
84
+ }
85
+
86
+
87
+ def write_span_concept_query(
88
+ app_id: str,
89
+ session_id: str,
90
+ span_id: str,
91
+ name: str,
92
+ concept_type: str = "",
93
+ properties: dict | None = None,
94
+ ) -> tuple[str, dict[str, Any]]:
95
+ """Build a MERGE query to attach a concept to a span node."""
96
+ query = """
97
+ MERGE (app:Application {applicationId: $app_id})
98
+ MERGE (app)-[:hasSession]->(session:Session {sessionId: $session_id})
99
+ MERGE (session)-[:hasSpan]->(span:Span {spanId: $span_id})
100
+ MERGE (span)-[:hasConcept]->(c:Concept {name: $name})
101
+ SET c.type = $concept_type
102
+ SET c += $properties
103
+ RETURN c.name AS name
104
+ """
105
+ return query, {
106
+ "app_id": app_id,
107
+ "session_id": session_id,
108
+ "span_id": span_id,
109
+ "name": name,
110
+ "concept_type": concept_type,
111
+ "properties": properties or {},
112
+ }