semantic-context-engine 0.3.0a1__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 (39) hide show
  1. semantic_context_engine/__init__.py +136 -0
  2. semantic_context_engine/artifacts.py +98 -0
  3. semantic_context_engine/cli.py +197 -0
  4. semantic_context_engine/compiler.py +316 -0
  5. semantic_context_engine/composition.py +31 -0
  6. semantic_context_engine/config.py +199 -0
  7. semantic_context_engine/diff.py +93 -0
  8. semantic_context_engine/domain_contracts.py +386 -0
  9. semantic_context_engine/engine.py +250 -0
  10. semantic_context_engine/enrichment.py +1416 -0
  11. semantic_context_engine/errors.py +291 -0
  12. semantic_context_engine/evaluation.py +88 -0
  13. semantic_context_engine/hierarchies.py +185 -0
  14. semantic_context_engine/instructions/semantic_catalog.md +2 -0
  15. semantic_context_engine/integration.py +22 -0
  16. semantic_context_engine/integrations/__init__.py +11 -0
  17. semantic_context_engine/integrations/langchain.py +275 -0
  18. semantic_context_engine/models.py +282 -0
  19. semantic_context_engine/normalization.py +351 -0
  20. semantic_context_engine/pipeline.py +1685 -0
  21. semantic_context_engine/prompts/v1/column_classification.md +15 -0
  22. semantic_context_engine/prompts/v1/grain_correction.md +4 -0
  23. semantic_context_engine/prompts/v1/relationship_proposal.md +10 -0
  24. semantic_context_engine/prompts/v1/synthesis.md +5 -0
  25. semantic_context_engine/prompts/v1/taxonomy.md +5 -0
  26. semantic_context_engine/publication.py +98 -0
  27. semantic_context_engine/registry.py +764 -0
  28. semantic_context_engine/relations.py +1114 -0
  29. semantic_context_engine/runtime.py +1193 -0
  30. semantic_context_engine/sources/base.py +130 -0
  31. semantic_context_engine/sources/duckdb.py +1172 -0
  32. semantic_context_engine/sources/fake.py +107 -0
  33. semantic_context_engine/storage.py +248 -0
  34. semantic_context_engine-0.3.0a1.dist-info/METADATA +263 -0
  35. semantic_context_engine-0.3.0a1.dist-info/RECORD +39 -0
  36. semantic_context_engine-0.3.0a1.dist-info/WHEEL +5 -0
  37. semantic_context_engine-0.3.0a1.dist-info/entry_points.txt +2 -0
  38. semantic_context_engine-0.3.0a1.dist-info/licenses/LICENSE +202 -0
  39. semantic_context_engine-0.3.0a1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,136 @@
1
+ # Core models (canonical - imported directly from semantic_context_engine.models)
2
+ from semantic_context_engine.models import (
3
+ ColumnMeta,
4
+ ObjectSnapshot,
5
+ StructuralSnapshot,
6
+ VariantKey,
7
+ RelationshipType,
8
+ ReviewStatus,
9
+ Overrides,
10
+ RelationshipOverride,
11
+ )
12
+
13
+ # Engine and source
14
+ from semantic_context_engine.engine import SemanticEngine
15
+ from semantic_context_engine.sources.base import (
16
+ Source,
17
+ SourceCapabilities,
18
+ GrainAggregateSource,
19
+ RelationshipAggregateSource,
20
+ MeteredRelationshipAggregateSource,
21
+ SemistructuredProfileSource,
22
+ BoundedSamplingSource,
23
+ ColumnStatisticsSource,
24
+ )
25
+ from semantic_context_engine.enrichment import (
26
+ StructuredLLM,
27
+ DeterministicFakeLLM,
28
+ EntitySemantic,
29
+ )
30
+ from semantic_context_engine.integrations.langchain import LangChainStructuredLLM
31
+
32
+ # Registry and storage
33
+ from semantic_context_engine.registry import Registry
34
+ from semantic_context_engine.storage import (
35
+ LocalStorage,
36
+ MemoryStorage,
37
+ StorageProtocol,
38
+ storage_from_uri,
39
+ )
40
+ from semantic_context_engine.runtime import RuntimeView
41
+ from semantic_context_engine.domain_contracts import (
42
+ SourceCapabilitiesContract,
43
+ SyncReportContract,
44
+ OverrideDocumentContract,
45
+ JsonProfilePolicyContract,
46
+ )
47
+ from semantic_context_engine.errors import (
48
+ SemanticContextError,
49
+ ValidationError,
50
+ ConfigurationError,
51
+ UnsupportedSnapshotVersionError,
52
+ SnapshotValidationError,
53
+ PublicationConflictError,
54
+ SourceError,
55
+ StorageError,
56
+ ProviderError,
57
+ UnsupportedCapabilityError,
58
+ AggregateQueryBudgetExceeded,
59
+ AggregateQueryExecutionError,
60
+ )
61
+ from semantic_context_engine.integration import append_tool_instructions
62
+ from semantic_context_engine.normalization import (
63
+ normalize_object_metadata,
64
+ compute_fingerprint,
65
+ )
66
+ from semantic_context_engine.diff import diff_structural
67
+
68
+
69
+ def load_view(
70
+ storage,
71
+ namespace: str,
72
+ ttl_seconds: int = 600,
73
+ *,
74
+ scope=None,
75
+ payload_budget_bytes: int = 65536,
76
+ ) -> RuntimeView:
77
+ """Construct a source/LLM-independent, read-only runtime catalog view."""
78
+ return RuntimeView.from_storage(
79
+ storage,
80
+ namespace,
81
+ ttl_seconds=ttl_seconds,
82
+ scope=scope,
83
+ payload_budget_bytes=payload_budget_bytes,
84
+ )
85
+
86
+
87
+ __all__ = [
88
+ "SemanticEngine",
89
+ "Source",
90
+ "SourceCapabilities",
91
+ "GrainAggregateSource",
92
+ "RelationshipAggregateSource",
93
+ "MeteredRelationshipAggregateSource",
94
+ "SemistructuredProfileSource",
95
+ "BoundedSamplingSource",
96
+ "ColumnStatisticsSource",
97
+ "StructuredLLM",
98
+ "DeterministicFakeLLM",
99
+ "LangChainStructuredLLM",
100
+ "EntitySemantic",
101
+ "Registry",
102
+ "LocalStorage",
103
+ "MemoryStorage",
104
+ "StorageProtocol",
105
+ "storage_from_uri",
106
+ "RuntimeView",
107
+ "SourceCapabilitiesContract",
108
+ "SyncReportContract",
109
+ "OverrideDocumentContract",
110
+ "JsonProfilePolicyContract",
111
+ "SemanticContextError",
112
+ "ValidationError",
113
+ "ConfigurationError",
114
+ "UnsupportedSnapshotVersionError",
115
+ "SnapshotValidationError",
116
+ "PublicationConflictError",
117
+ "SourceError",
118
+ "StorageError",
119
+ "ProviderError",
120
+ "UnsupportedCapabilityError",
121
+ "AggregateQueryBudgetExceeded",
122
+ "AggregateQueryExecutionError",
123
+ "append_tool_instructions",
124
+ "load_view",
125
+ "ObjectSnapshot",
126
+ "StructuralSnapshot",
127
+ "ColumnMeta",
128
+ "VariantKey",
129
+ "RelationshipType",
130
+ "ReviewStatus",
131
+ "Overrides",
132
+ "RelationshipOverride",
133
+ "normalize_object_metadata",
134
+ "compute_fingerprint",
135
+ "diff_structural",
136
+ ]
@@ -0,0 +1,98 @@
1
+ """Validated serialized artifact contracts and explicit alpha migration policy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pydantic import (
8
+ BaseModel,
9
+ ConfigDict,
10
+ Field,
11
+ ValidationError as PydanticValidationError,
12
+ )
13
+
14
+ from semantic_context_engine.errors import (
15
+ SnapshotValidationError,
16
+ UnsupportedSnapshotVersionError,
17
+ )
18
+
19
+
20
+ class ColumnArtifact(BaseModel):
21
+ model_config = ConfigDict(extra="forbid", strict=True)
22
+ name: str
23
+ data_type: str
24
+ nullable: bool = True
25
+ comment: str | None = None
26
+
27
+
28
+ class ObjectArtifact(BaseModel):
29
+ model_config = ConfigDict(extra="forbid", strict=True)
30
+ key: str
31
+ fqn: str
32
+ object_type: str
33
+ description: str | None = None
34
+ hint: str | None = None
35
+ table_comment: str | None = None
36
+ columns: dict[str, ColumnArtifact]
37
+ ddl_canonical: str
38
+ ddl_raw: str = ""
39
+ ddl_error: str | None = None
40
+ dependencies: list[str] = Field(default_factory=list)
41
+ variant_keys: list[dict[str, Any]] = Field(default_factory=list)
42
+ declared_constraints: list[dict[str, Any]] = Field(default_factory=list)
43
+ fingerprint: str
44
+ discovered_at: str = ""
45
+
46
+
47
+ class StructuralArtifact(BaseModel):
48
+ model_config = ConfigDict(extra="forbid", strict=True)
49
+ schema_version: int = 1
50
+ version: str
51
+ published_at: str | None = None
52
+ objects: dict[str, ObjectArtifact]
53
+ discovered_order: list[str] = Field(default_factory=list)
54
+
55
+
56
+ def validate_structural_artifact(data: dict[str, Any]) -> StructuralArtifact:
57
+ """Validate schema v1; explicitly migrate the documented pre-version alpha shape.
58
+
59
+ Missing schema_version is the only legacy signal supported. That shape is
60
+ validated and defaulted in memory; persisted bytes are never rewritten here.
61
+ Unknown versions/fields fail closed.
62
+ """
63
+ if not isinstance(data, dict):
64
+ raise SnapshotValidationError("Structural artifact must be a JSON object")
65
+ version = data.get("schema_version", 0)
66
+ if type(version) is not int or version not in (0, 1):
67
+ raise UnsupportedSnapshotVersionError(
68
+ f"Unsupported structural snapshot schema_version {version!r}; export and rebuild with a supported release"
69
+ )
70
+ normalized = dict(data)
71
+ if version == 0:
72
+ normalized["schema_version"] = 1
73
+ normalized.setdefault("discovered_order", [])
74
+ if isinstance(normalized.get("objects"), dict):
75
+ migrated_objects = {}
76
+ for key, raw in normalized["objects"].items():
77
+ if not isinstance(raw, dict):
78
+ migrated_objects[key] = raw
79
+ continue
80
+ item = dict(raw)
81
+ item.setdefault("ddl_raw", "")
82
+ item.setdefault("ddl_error", None)
83
+ item.setdefault("dependencies", [])
84
+ item.setdefault("variant_keys", [])
85
+ item.setdefault("declared_constraints", [])
86
+ item.setdefault("discovered_at", "")
87
+ migrated_objects[key] = item
88
+ normalized["objects"] = migrated_objects
89
+ try:
90
+ artifact = StructuralArtifact.model_validate(normalized)
91
+ except PydanticValidationError as exc:
92
+ raise SnapshotValidationError(f"Invalid structural snapshot artifact: {exc}") from exc
93
+ for key, obj in artifact.objects.items():
94
+ if key != obj.key:
95
+ raise SnapshotValidationError(
96
+ "Structural artifact object key does not match its mapping key"
97
+ )
98
+ return artifact
@@ -0,0 +1,197 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from semantic_context_engine.errors import safe_error_label
6
+ from typing import Optional
7
+
8
+ from semantic_context_engine.config import load_config, SemanticEngine
9
+ from semantic_context_engine.models import StructuralSnapshot
10
+
11
+
12
+ def main(argv: Optional[list] = None) -> int:
13
+ """CLI da semantic layer.
14
+
15
+ Comandos:
16
+ semantic sync [--profile-variants] - descobre, compara e imprime relatório (dry-run)
17
+ semantic sync --publish - idem e publica se houver mudança sem falha
18
+ semantic inspect [--version V] - resume o snapshot ativo ou especificado
19
+ semantic activate V - rollback/roll-forward do ponteiro
20
+ semantic overrides pull | push ARQ - lê / valida e grava os overrides
21
+ """
22
+ import argparse
23
+
24
+ parser = argparse.ArgumentParser(prog="semantic", description="Semantic layer for AI agents")
25
+ subparsers = parser.add_subparsers(dest="command", help="Comandos disponíveis")
26
+
27
+ # sync
28
+ sync_parser = subparsers.add_parser("sync", help="Sync metadados")
29
+ sync_parser.add_argument(
30
+ "--publish", action="store_true", help="Publicar se houver mudança viável"
31
+ )
32
+ sync_parser.add_argument(
33
+ "--relations", action="store_true", help="Validar relações entre objetos"
34
+ )
35
+ sync_parser.add_argument(
36
+ "--recompute-relations",
37
+ action="store_true",
38
+ help="Recalcular relações mesmo quando os pares não mudaram",
39
+ )
40
+
41
+ # inspect
42
+ inspect_parser = subparsers.add_parser("inspect", help="Inspect snapshot")
43
+ inspect_parser.add_argument(
44
+ "--version", type=str, default=None, help="Versão específica para inspecionar"
45
+ )
46
+
47
+ # activate
48
+ activate_parser = subparsers.add_parser("activate", help="Ativar versão")
49
+ activate_parser.add_argument("version", type=str, help="Versão para ativar")
50
+
51
+ # overrides
52
+ overrides_parser = subparsers.add_parser("overrides", help="Gerenciar overrides")
53
+ overrides_sub = overrides_parser.add_subparsers(dest="overrides_cmd")
54
+
55
+ overrides_pull = overrides_sub.add_parser("pull", help="Pull overrides do storage")
56
+ overrides_pull.add_argument("file", type=str, help="Arquivo para gravar overrides")
57
+
58
+ overrides_push = overrides_sub.add_parser("push", help="Push overrides para storage")
59
+ overrides_push.add_argument("file", type=str, help="Arquivo com overrides para aplicar")
60
+
61
+ args = parser.parse_args(argv)
62
+
63
+ if not args.command:
64
+ parser.print_help()
65
+ return 1
66
+
67
+ # Procurar config sem quebrar: tenta semantic.yaml cwd, depois env var, depois fallback
68
+ config_path = None
69
+ for candidate in ["semantic.yaml", os.path.join(os.getcwd(), "semantic.yaml")]:
70
+ if os.path.exists(candidate):
71
+ config_path = candidate
72
+ break
73
+ if config_path is None:
74
+ # Tenta ler de variável de ambiente
75
+ env_path = os.environ.get("SEMAPHORE_YAML_PATH", "")
76
+ if env_path and os.path.exists(env_path):
77
+ config_path = env_path
78
+ if config_path is None:
79
+ print("Erro: arquivo de configuração 'semantic.yaml' não encontrado.")
80
+ print("Coloque semantic.yaml no diretório atual ou defina SEMAPHORE_YAML_PATH.")
81
+ return 1
82
+
83
+ try:
84
+ config = load_config(config_path)
85
+ except Exception:
86
+ print("Erro ao carregar configuração (invalid_configuration).")
87
+ return 1
88
+
89
+ try:
90
+ engine = SemanticEngine(config)
91
+ except Exception:
92
+ print("Erro ao inicializar engine (configuration_or_backend_unavailable).")
93
+ return 1
94
+
95
+ if args.command == "sync":
96
+ try:
97
+ report = engine.sync(
98
+ publish=args.publish,
99
+ relations=args.relations,
100
+ recompute_relations=args.recompute_relations,
101
+ )
102
+ except Exception as e:
103
+ # Keep the CLI contract actionable while never reflecting backend
104
+ # exception text (which may contain credentials or query data).
105
+ error_label = safe_error_label(e)
106
+ report = {
107
+ "status": "failed",
108
+ "baseline": None,
109
+ "candidate": None,
110
+ "added": [],
111
+ "changed": {},
112
+ "removed": [],
113
+ "unchanged": [],
114
+ "failed": {"sync": error_label},
115
+ "override_conflicts": [],
116
+ }
117
+ print_json(report)
118
+ return 1 if report.get("status") == "failed" else 0
119
+
120
+ if args.command == "inspect":
121
+ version = args.version
122
+ try:
123
+ snapshot = (
124
+ engine._registry.load_snapshot(version)
125
+ if version
126
+ else engine._registry.load_active()
127
+ )
128
+ except Exception as exc:
129
+ print(f"Snapshot indisponível ({safe_error_label(exc)}).")
130
+ return 1
131
+ if snapshot is None:
132
+ print("Nenhum snapshot encontrado.")
133
+ return 1
134
+ print_structural(snapshot)
135
+ return 0
136
+
137
+ if args.command == "activate":
138
+ try:
139
+ snapshot = engine._registry.activate_version(args.version)
140
+ print(f"Ativado snapshot v{snapshot.version}")
141
+ return 0
142
+ except Exception as e:
143
+ print(f"Erro ao ativar snapshot ({safe_error_label(e)}).")
144
+ return 1
145
+
146
+ if args.command == "overrides":
147
+ try:
148
+ if args.overrides_cmd == "pull":
149
+ filepath = args.file
150
+ import yaml
151
+
152
+ data = engine._registry.load_overrides()
153
+ with open(filepath, "w", encoding="utf-8") as f:
154
+ yaml.safe_dump(data, f, allow_unicode=True, sort_keys=False)
155
+ print("Overrides exportados.")
156
+ elif args.overrides_cmd == "push":
157
+ import yaml
158
+
159
+ filepath = args.file
160
+ with open(filepath, "r", encoding="utf-8") as f:
161
+ data = yaml.safe_load(f)
162
+ engine._registry.save_overrides(data)
163
+ print("Overrides aplicados.")
164
+ except Exception as exc:
165
+ print(f"Falha em overrides ({safe_error_label(exc)}).")
166
+ return 1
167
+ return 0
168
+
169
+ return 1
170
+
171
+
172
+ def print_json(report: dict) -> None:
173
+ """Imprime relatório como JSON formatado."""
174
+ import json
175
+
176
+ print(json.dumps(report, indent=2, ensure_ascii=False))
177
+
178
+
179
+ def print_structural(snapshot: StructuralSnapshot) -> None:
180
+ """Imprime estrutura de snapshot legível."""
181
+ print(f"Versão: {snapshot.version}")
182
+ print(f"Publicado em: {snapshot.published_at}")
183
+ print(f"Objetos ({len(snapshot.objects)}):")
184
+ for key, obj in snapshot.objects.items():
185
+ print(f" - {key}:")
186
+ print(f" FQN: {obj.fqn}")
187
+ print(f" Tipo: {obj.object_type}")
188
+ print(f" Fingerprint: {obj.fingerprint}")
189
+ print(f" Colunas: {list(obj.columns.keys())}")
190
+ if obj.dependencies:
191
+ print(f" Dependências: {obj.dependencies}")
192
+ if obj.variant_keys:
193
+ print(f" Variant keys: {[(vk.column, vk.key) for vk in obj.variant_keys]}")
194
+
195
+
196
+ if __name__ == "__main__":
197
+ sys.exit(main())