codemie-cdk-python 0.1.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 (40) hide show
  1. codemie_cdk_python-0.1.0.dist-info/METADATA +892 -0
  2. codemie_cdk_python-0.1.0.dist-info/RECORD +40 -0
  3. codemie_cdk_python-0.1.0.dist-info/WHEEL +4 -0
  4. codemie_cdk_python-0.1.0.dist-info/entry_points.txt +3 -0
  5. codemie_iac/__init__.py +49 -0
  6. codemie_iac/cli/__init__.py +17 -0
  7. codemie_iac/cli/__main__.py +24 -0
  8. codemie_iac/cli/commands/__init__.py +17 -0
  9. codemie_iac/cli/commands/apply.py +119 -0
  10. codemie_iac/cli/commands/plan.py +72 -0
  11. codemie_iac/cli/config_model.py +136 -0
  12. codemie_iac/cli/documents.py +59 -0
  13. codemie_iac/cli/env_file.py +62 -0
  14. codemie_iac/cli/exit_status.py +80 -0
  15. codemie_iac/cli/init_command.py +101 -0
  16. codemie_iac/cli/main.py +152 -0
  17. codemie_iac/cli/render.py +206 -0
  18. codemie_iac/cli/target_config.py +258 -0
  19. codemie_iac/credentials.py +99 -0
  20. codemie_iac/envelope.py +188 -0
  21. codemie_iac/plan_apply/__init__.py +70 -0
  22. codemie_iac/plan_apply/bulk_create.py +561 -0
  23. codemie_iac/plan_apply/credentials.py +306 -0
  24. codemie_iac/plan_apply/errors.py +223 -0
  25. codemie_iac/plan_apply/field_policy.py +188 -0
  26. codemie_iac/plan_apply/guards.py +221 -0
  27. codemie_iac/plan_apply/kinds.py +815 -0
  28. codemie_iac/plan_apply/lookup.py +313 -0
  29. codemie_iac/plan_apply/ordering.py +177 -0
  30. codemie_iac/plan_apply/single_apply.py +751 -0
  31. codemie_iac/resolver.py +61 -0
  32. codemie_iac/schema.py +106 -0
  33. codemie_iac/serializer.py +64 -0
  34. codemie_iac/specs/__init__.py +13 -0
  35. codemie_iac/specs/assistant.py +509 -0
  36. codemie_iac/specs/category.py +36 -0
  37. codemie_iac/specs/datasource.py +595 -0
  38. codemie_iac/specs/integration.py +103 -0
  39. codemie_iac/specs/skill.py +51 -0
  40. codemie_iac/specs/workflow.py +154 -0
@@ -0,0 +1,258 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Target project and platform connection settings for the plan/apply CLI.
16
+
17
+ Every connection setting comes from ``codemie.yaml`` (``project.name`` and the
18
+ ``environment:`` mapping), except ``--project``, which overrides the project.
19
+ String values in the file may reference ``${NAME}`` / ``${NAME:-default}``; the
20
+ real environment and a ``.env`` file only feed those references and the
21
+ ``env:NAME`` credentials of the documents.
22
+ """
23
+
24
+ import os
25
+ import re
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Mapping, Optional
28
+
29
+ import yaml
30
+ from codemie_sdk import CodeMieClient
31
+
32
+ from .config_model import ConfigError, EnvironmentSection, load_config
33
+ from .env_file import read_env_file
34
+
35
+ __all__ = ["ConfigError", "TargetConfig", "DEFAULT_CONFIG_PATH", "is_local_url"]
36
+
37
+ DEFAULT_CONFIG_PATH = "./codemie.yaml"
38
+ DEFAULT_ENV_FILE = "./.env"
39
+
40
+ _VAR = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}")
41
+ _LOCAL_MARKERS = ("localhost", "127.0.0.1", "0.0.0.0", "192.168")
42
+ _CLIENT_PAIR = (
43
+ ("client_id", "auth_client_id"),
44
+ ("client_secret", "auth_client_secret"),
45
+ )
46
+ _USER_PAIR = (("username", "username"), ("password", "password"))
47
+
48
+
49
+ def is_local_url(url: str) -> bool:
50
+ """Same rule as the SDK: the lower-cased URL contains a local marker."""
51
+ lowered = url.lower()
52
+ return any(marker in lowered for marker in _LOCAL_MARKERS)
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class LoginPlan:
57
+ """How to log in: ``local``, ``client_credentials`` or ``password``."""
58
+
59
+ kind: str
60
+ client_args: Mapping[str, str] = field(repr=False)
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class TargetConfig:
65
+ """Resolved target project and client connection settings."""
66
+
67
+ project: str
68
+ _login: LoginPlan = field(repr=False)
69
+ _verify_ssl: bool = True
70
+ _environ: Mapping[str, str] = field(default_factory=dict, repr=False)
71
+ warnings: tuple[str, ...] = ()
72
+
73
+ @classmethod
74
+ def resolve(
75
+ cls,
76
+ project_flag: Optional[str],
77
+ config_path: Optional[str],
78
+ environ: Optional[Mapping[str, str]] = None,
79
+ env_file: Optional[str] = None,
80
+ ) -> "TargetConfig":
81
+ """Read ``codemie.yaml``; ``--project`` overrides ``project.name``."""
82
+ real = os.environ if environ is None else environ
83
+ env = {**_load_env_file(env_file), **real}
84
+ path = config_path or DEFAULT_CONFIG_PATH
85
+ warnings: list[str] = []
86
+ try:
87
+ return cls._build(project_flag, path, env, warnings)
88
+ except ConfigError as exc:
89
+ if not exc.warnings:
90
+ exc.warnings = tuple(warnings)
91
+ raise
92
+
93
+ @classmethod
94
+ def _build(
95
+ cls,
96
+ project_flag: Optional[str],
97
+ path: str,
98
+ env: Mapping[str, str],
99
+ warnings: list[str],
100
+ ) -> "TargetConfig":
101
+ document = _expand(_load_document(path), env)
102
+ config, found = load_config(document)
103
+ warnings.extend(found)
104
+ project = project_flag or config.project.name
105
+ if not project:
106
+ raise ConfigError(
107
+ f"Missing project: use --project or set project.name in {path}"
108
+ )
109
+ settings = config.environment
110
+ if not settings.codemie_api_url:
111
+ raise ConfigError(f"Missing environment.codemie_api_url in {path}")
112
+ if not settings.verify_ssl:
113
+ warnings.append(
114
+ "environment.verify_ssl is false: TLS certificates are not verified"
115
+ )
116
+ return cls(
117
+ project=project,
118
+ _login=_login_plan(settings),
119
+ _verify_ssl=settings.verify_ssl,
120
+ _environ=env,
121
+ warnings=tuple(warnings),
122
+ )
123
+
124
+ @property
125
+ def environment(self) -> Mapping[str, str]:
126
+ """Real environment merged over ``.env``; what ``env:NAME`` credentials read."""
127
+ return self._environ
128
+
129
+ def build_client(self) -> CodeMieClient:
130
+ """Construct the platform client from the stored login plan."""
131
+ return CodeMieClient(**self._login.client_args, verify_ssl=self._verify_ssl)
132
+
133
+
134
+ def _pair_args(
135
+ settings: EnvironmentSection, pair: tuple[tuple[str, str], ...]
136
+ ) -> dict[str, str]:
137
+ values = {arg: getattr(settings, key) for key, arg in pair}
138
+ return values if all(values.values()) else {}
139
+
140
+
141
+ def _has_any(settings: EnvironmentSection, pair: tuple[tuple[str, str], ...]) -> bool:
142
+ return any(getattr(settings, key) for key, _ in pair)
143
+
144
+
145
+ def _missing(settings: EnvironmentSection, keys: tuple[str, ...]) -> list[str]:
146
+ return [f"environment.{key}" for key in keys if not getattr(settings, key)]
147
+
148
+
149
+ def _local_plan(settings: EnvironmentSection) -> LoginPlan:
150
+ missing = _missing(settings, ("username", "password"))
151
+ if missing:
152
+ raise ConfigError(
153
+ "A local codemie_api_url needs username and password; missing "
154
+ + ", ".join(missing)
155
+ )
156
+ # The SDK constructor requires the two Keycloak arguments even for a local URL.
157
+ args = {
158
+ "codemie_api_domain": settings.codemie_api_url,
159
+ "auth_server_url": "",
160
+ "auth_realm_name": "",
161
+ }
162
+ return LoginPlan("local", {**args, **_pair_args(settings, _USER_PAIR)})
163
+
164
+
165
+ def _remote_plan(settings: EnvironmentSection) -> LoginPlan:
166
+ """Keycloak login: client_id + client_secret, or client_id + username + password."""
167
+ missing = _missing(settings, ("auth_server_url", "auth_realm_name", "client_id"))
168
+ uses_secret = bool(settings.client_secret)
169
+ if not uses_secret:
170
+ if _has_any(settings, _USER_PAIR):
171
+ missing += _missing(settings, ("username", "password"))
172
+ else:
173
+ missing.append(
174
+ "environment.client_secret "
175
+ "(or environment.username and environment.password)"
176
+ )
177
+ if missing:
178
+ raise ConfigError("A remote login is incomplete; missing " + ", ".join(missing))
179
+ if uses_secret and _has_any(settings, _USER_PAIR):
180
+ raise ConfigError(
181
+ "A remote login is ambiguous: set environment.client_secret or "
182
+ "environment.username and environment.password, not both"
183
+ )
184
+ args = {
185
+ "codemie_api_domain": settings.codemie_api_url,
186
+ "auth_server_url": settings.auth_server_url,
187
+ "auth_realm_name": settings.auth_realm_name,
188
+ "auth_client_id": settings.client_id,
189
+ }
190
+ if uses_secret:
191
+ return LoginPlan(
192
+ "client_credentials", {**args, "auth_client_secret": settings.client_secret}
193
+ )
194
+ return LoginPlan("password", {**args, **_pair_args(settings, _USER_PAIR)})
195
+
196
+
197
+ def _login_plan(settings: EnvironmentSection) -> LoginPlan:
198
+ if is_local_url(settings.codemie_api_url):
199
+ return _local_plan(settings)
200
+ return _remote_plan(settings)
201
+
202
+
203
+ def _load_document(path: str) -> dict[str, Any]:
204
+ """Parse the config file; a missing file is a config error."""
205
+ try:
206
+ with open(path, encoding="utf-8") as handle:
207
+ data = yaml.safe_load(handle)
208
+ except (OSError, UnicodeDecodeError):
209
+ raise ConfigError(f"Config file {path} cannot be read") from None
210
+ except yaml.YAMLError:
211
+ raise ConfigError(f"Config file {path} is not valid YAML") from None
212
+ if data is None:
213
+ return {}
214
+ if not isinstance(data, dict):
215
+ raise ConfigError(f"Config file {path} must contain a YAML mapping")
216
+ return data
217
+
218
+
219
+ def _load_env_file(env_file: Optional[str]) -> dict[str, str]:
220
+ """Read ``.env``; only a missing *default* file is tolerated."""
221
+ explicit = env_file is not None
222
+ path = env_file if explicit else DEFAULT_ENV_FILE
223
+ try:
224
+ return read_env_file(path)
225
+ except FileNotFoundError:
226
+ if explicit:
227
+ raise ConfigError(f"Env file {path} cannot be read") from None
228
+ return {}
229
+ except (OSError, UnicodeDecodeError):
230
+ raise ConfigError(f"Env file {path} cannot be read") from None
231
+
232
+
233
+ def _substitute(match: "re.Match[str]", env: Mapping[str, str]) -> str:
234
+ name, default = match.group(1), match.group(2)
235
+ found = env.get(name)
236
+ if found:
237
+ return found
238
+ if default is None:
239
+ raise ConfigError(
240
+ f"codemie.yaml references ${{{name}}}, which is not set "
241
+ f"(use ${{{name}:-}} to allow an empty value)"
242
+ )
243
+ return default
244
+
245
+
246
+ def _expand(value: Any, env: Mapping[str, str]) -> Any:
247
+ """Expand ``${NAME}`` / ``${NAME:-default}`` in every string, recursively.
248
+
249
+ A ``${NAME}`` that is unset or empty is a config error; ``${NAME:-}`` is how
250
+ a value is allowed to be empty.
251
+ """
252
+ if isinstance(value, str):
253
+ return _VAR.sub(lambda m: _substitute(m, env), value)
254
+ if isinstance(value, dict):
255
+ return {key: _expand(item, env) for key, item in value.items()}
256
+ if isinstance(value, list):
257
+ return [_expand(item, env) for item in value]
258
+ return value
@@ -0,0 +1,99 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import re
16
+ import threading
17
+ from pydantic import RootModel, model_validator
18
+
19
+ # CR-001: the shape check alone (`<alnum>+:<alnum/underscore>+`) accepts any
20
+ # colon-delimited literal with a lowercase-alnum prefix -- including a secret
21
+ # string that happens to be formatted that way. Restricting the prefix to a
22
+ # known, closed set of reference sources means an arbitrary literal cannot
23
+ # coincidentally satisfy the reference shape; "env" is the only source this
24
+ # module currently produces (via `from_entity`).
25
+ _REF_PATTERN = re.compile(r"^(?P<source>[a-z0-9]+):(?P<identifier>[A-Za-z0-9_]+)$")
26
+ _KNOWN_SOURCES = frozenset({"env"})
27
+
28
+ # CR-002: `from_entity`'s sanitization is intentionally lossy (distinct
29
+ # identifiers that differ only in punctuation collapse to the same output --
30
+ # see test_from_entity_sanitizes_non_alphanumeric), so two genuinely distinct
31
+ # (identifier, credential_key) pairs can collide onto the same CredentialRef
32
+ # string. The information needed to detect that (the original, pre-sanitized
33
+ # pair) only exists at the moment `from_entity` is called -- once a Bundle
34
+ # holds the final ref string, that provenance is gone. This process-lifetime
35
+ # registry remembers which pair produced which ref string, and raises if a
36
+ # *different* pair ever produces one already claimed by another pair. Calling
37
+ # `from_entity` again with the exact same pair (determinism, AC8) is not a
38
+ # collision and never raises.
39
+ _SEEN_REFS_LOCK = threading.Lock()
40
+ _SEEN_REFS: dict[str, tuple[str, str]] = {}
41
+
42
+
43
+ class CredentialRef(RootModel[str]):
44
+ @model_validator(mode="after")
45
+ def _check_format(self) -> "CredentialRef":
46
+ match = _REF_PATTERN.fullmatch(self.root)
47
+ if not match or match.group("source") not in _KNOWN_SOURCES:
48
+ raise ValueError(
49
+ "CredentialRef must match '<source>:<identifier>' with a "
50
+ f"known source {sorted(_KNOWN_SOURCES)!r}, got {self.root!r}"
51
+ )
52
+ return self
53
+
54
+ @classmethod
55
+ def from_entity(cls, identifier: str, credential_key: str) -> "CredentialRef":
56
+ def sanitize(value: str) -> str:
57
+ return re.sub(r"[^A-Za-z0-9]+", "_", value)
58
+
59
+ sanitized_id = sanitize(identifier).upper()
60
+ sanitized_key = sanitize(credential_key).upper()
61
+ if not any(c.isalnum() for c in sanitized_id) or not any(
62
+ c.isalnum() for c in sanitized_key
63
+ ):
64
+ raise ValueError(
65
+ "CredentialRef.from_entity requires identifier and "
66
+ "credential_key to each contain at least one alphanumeric "
67
+ f"character, got identifier={identifier!r}, "
68
+ f"credential_key={credential_key!r}"
69
+ )
70
+
71
+ ref_string = f"env:{sanitized_id}_{sanitized_key}"
72
+ pair = (identifier, credential_key)
73
+ with _SEEN_REFS_LOCK:
74
+ existing = _SEEN_REFS.get(ref_string)
75
+ if existing is not None and existing != pair:
76
+ raise ValueError(
77
+ f"CredentialRef collision: identifier/credential_key "
78
+ f"pairs {existing!r} and {pair!r} both sanitize to "
79
+ f"{ref_string!r}; use more distinguishable identifiers "
80
+ "or credential keys."
81
+ )
82
+ _SEEN_REFS[ref_string] = pair
83
+ return cls(ref_string)
84
+
85
+
86
+ def reset_registry() -> None:
87
+ """Clear the process-lifetime collision registry (CR-001).
88
+
89
+ ``_SEEN_REFS`` otherwise accumulates for the lifetime of the process,
90
+ with no bound and no scoping to any particular ``Bundle``. A long-running
91
+ host that builds many logically unrelated ``Bundle``s over its lifetime
92
+ should call this between them: without it, memory grows without bound,
93
+ and two unrelated batches that happen to reuse the same
94
+ ``(identifier, credential_key)`` pair for genuinely different secrets
95
+ would spuriously collide -- or silently share a ref -- across batches
96
+ that have nothing to do with each other.
97
+ """
98
+ with _SEEN_REFS_LOCK:
99
+ _SEEN_REFS.clear()
@@ -0,0 +1,188 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Document envelope types shared by all IaC document kinds.
16
+
17
+ ``DocumentMeta`` carries the document's ``kind``/``name`` discriminator,
18
+ ``Document`` wraps a concrete ``*Spec`` payload with that metadata, and
19
+ ``Bundle`` is an ordered collection of ``Document`` instances (potentially
20
+ mixing different ``kind``s) that round-trips through ``model_dump``.
21
+ """
22
+
23
+ from enum import Enum
24
+ from typing import Any, Union, get_args, get_origin
25
+
26
+ from pydantic import BaseModel, ConfigDict, RootModel, TypeAdapter, model_validator
27
+
28
+ from .specs.assistant import AssistantSpec
29
+ from .specs.category import CategorySpec
30
+ from .specs.datasource import DatasourceSpec
31
+ from .specs.integration import IntegrationSpec
32
+ from .specs.skill import SkillSpec
33
+ from .specs.workflow import WorkflowSpec
34
+
35
+
36
+ class DocumentKind(str, Enum):
37
+ """The closed set of resource kinds a ``Document`` can hold.
38
+
39
+ Unlike ``*Spec.type`` (e.g. ``DatasourceSpec``'s nine-way discriminator),
40
+ this is not a pydantic discriminated-union tag -- ``Document._dispatch_spec``
41
+ below looks ``meta.kind`` up in ``_SPEC_BY_KIND`` manually, before pydantic's
42
+ own union resolution ever runs (see that method's docstring for why). So
43
+ there is no discriminated-union convention pulling this towards ``Literal``;
44
+ it is just a fixed vocabulary, which is what ``Enum`` is for.
45
+ """
46
+
47
+ ASSISTANT = "assistant"
48
+ DATASOURCE = "datasource"
49
+ INTEGRATION = "integration"
50
+ SKILL = "skill"
51
+ CATEGORY = "category"
52
+ WORKFLOW = "workflow"
53
+
54
+
55
+ _SPEC_BY_KIND = {
56
+ DocumentKind.ASSISTANT: AssistantSpec,
57
+ DocumentKind.DATASOURCE: DatasourceSpec,
58
+ DocumentKind.INTEGRATION: IntegrationSpec,
59
+ DocumentKind.SKILL: SkillSpec,
60
+ DocumentKind.CATEGORY: CategorySpec,
61
+ DocumentKind.WORKFLOW: WorkflowSpec,
62
+ }
63
+
64
+
65
+ def _spec_classes(spec_type) -> tuple[type, ...]:
66
+ """Concrete spec classes behind a ``_SPEC_BY_KIND`` entry.
67
+
68
+ ``isinstance`` rejects a subscripted generic, and ``DatasourceSpec`` is an
69
+ ``Annotated[Union[...]]`` of per-type specs, so unwrap it into the plain
70
+ member classes. A plain class unwraps to itself.
71
+ """
72
+ if get_origin(spec_type) is Union:
73
+ return tuple(
74
+ cls for member in get_args(spec_type) for cls in _spec_classes(member)
75
+ )
76
+ args = get_args(spec_type)
77
+ if args: # Annotated[X, ...] -> its first argument is the wrapped type
78
+ return _spec_classes(args[0])
79
+ return (spec_type,)
80
+
81
+
82
+ # Validation errors must never echo input values: a datasource document can
83
+ # carry a literal secret that the offline name check rejects.
84
+ _HIDE_INPUT = ConfigDict(hide_input_in_errors=True)
85
+
86
+
87
+ def _spec_adapter(spec_cls: Any) -> TypeAdapter:
88
+ """Adapter for ``spec_cls``; unions (not plain models) accept a config."""
89
+ if isinstance(spec_cls, type):
90
+ return TypeAdapter(spec_cls)
91
+ return TypeAdapter(spec_cls, config=_HIDE_INPUT)
92
+
93
+
94
+ class DocumentMeta(BaseModel):
95
+ """Discriminator metadata attached to every ``Document``."""
96
+
97
+ model_config = ConfigDict(extra="forbid")
98
+
99
+ kind: DocumentKind
100
+ name: str
101
+
102
+
103
+ class Document(BaseModel):
104
+ """A single IaC document: version, metadata, and a kind-specific spec.
105
+
106
+ ``meta.kind`` is the real discriminator for ``spec`` -- several Spec
107
+ classes share field names (e.g. ``name``/``description``), so letting
108
+ pydantic's own union resolution try each member in turn could silently
109
+ pick the wrong one, or surface an unhelpful "no match in union" error
110
+ instead of naming the actual offending field. The before-validator below
111
+ uses ``meta.kind`` to select and pre-validate the correct Spec class
112
+ before pydantic's union logic ever runs, so an unknown field inside
113
+ ``spec`` is reported by that Spec's own ``extra="forbid"`` validation
114
+ (naming the field) rather than by the union as a whole.
115
+ """
116
+
117
+ model_config = ConfigDict(extra="forbid", hide_input_in_errors=True)
118
+
119
+ version: str
120
+ meta: DocumentMeta
121
+ spec: (
122
+ AssistantSpec
123
+ | DatasourceSpec
124
+ | IntegrationSpec
125
+ | SkillSpec
126
+ | CategorySpec
127
+ | WorkflowSpec
128
+ )
129
+
130
+ @model_validator(mode="before")
131
+ @classmethod
132
+ def _dispatch_spec(cls, data):
133
+ if isinstance(data, dict) and isinstance(data.get("spec"), dict):
134
+ # CR-003: `meta` can be present but not a dict (e.g. a malformed
135
+ # hand-edited document with `meta: "oops"`) -- `.get("kind")` on
136
+ # a non-dict truthy value raises an uncaught AttributeError
137
+ # instead of letting normal field validation report a clean
138
+ # ValidationError naming `meta`. Guard explicitly instead.
139
+ meta = data.get("meta")
140
+ kind = meta.get("kind") if isinstance(meta, dict) else None
141
+ # `kind` is still caller-controlled, untyped data at this point
142
+ # (e.g. `meta: {kind: ["x"]}`) -- `dict.get` on an unhashable
143
+ # value raises a raw TypeError instead of a clean ValidationError
144
+ # naming `meta.kind`, which normal field validation produces once
145
+ # this before-validator steps aside and lets it run.
146
+ try:
147
+ spec_cls = _SPEC_BY_KIND.get(kind)
148
+ except TypeError:
149
+ spec_cls = None
150
+ if spec_cls is not None:
151
+ data = {
152
+ **data,
153
+ "spec": _spec_adapter(spec_cls).validate_python(data["spec"]),
154
+ }
155
+ return data
156
+
157
+ @model_validator(mode="after")
158
+ def _check_spec_matches_kind(self) -> "Document":
159
+ """Reject a `spec` whose type doesn't match `meta.kind`.
160
+
161
+ `_dispatch_spec` above only resolves `spec`'s type when it arrives as
162
+ a raw dict (the YAML-loading path). A `Document` built from model
163
+ instances skips that dispatch entirely, and pydantic's union
164
+ resolution accepts a value that's already an instance of one of the
165
+ union's members as-is -- so `Document(meta=DocumentMeta(kind="skill",
166
+ ...), spec=CategorySpec(...))` would otherwise validate with a
167
+ `spec` that doesn't match its own `meta.kind`, and `to_yaml` would
168
+ write a kind/body mismatch that `from_yaml` then rejects.
169
+ """
170
+ expected = _SPEC_BY_KIND[self.meta.kind]
171
+ classes = _spec_classes(expected)
172
+ if not isinstance(self.spec, classes):
173
+ names = " | ".join(cls.__name__ for cls in classes)
174
+ raise ValueError(
175
+ f"meta.kind={self.meta.kind.value!r} requires spec to be a "
176
+ f"{names}, got {type(self.spec).__name__}"
177
+ )
178
+ return self
179
+
180
+
181
+ class Bundle(RootModel[list[Document]]):
182
+ """An ordered collection of ``Document`` instances, possibly mixed-kind."""
183
+
184
+ def __iter__(self):
185
+ return iter(self.root)
186
+
187
+ def __len__(self):
188
+ return len(self.root)
@@ -0,0 +1,70 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .bulk_create import (
16
+ BulkCreator,
17
+ BulkCreateReport,
18
+ CreatedEntity,
19
+ FailedEntity,
20
+ )
21
+ from .credentials import EnvCredentialResolver, SecretValue
22
+ from .errors import (
23
+ ApplyError,
24
+ FieldError,
25
+ PlatformRejectionError,
26
+ UnresolvableCredentialError,
27
+ UnresolvedReferenceError,
28
+ )
29
+ from .field_policy import FIELD_POLICIES, FieldPolicy
30
+ from .guards import guard_datasource_identity, guard_supported
31
+ from .kinds import ADAPTERS, KindAdapter, adapter_for
32
+ from .lookup import NameLookup
33
+ from .ordering import DependencyGraph
34
+ from .single_apply import (
35
+ ApplyResult,
36
+ CannotCompare,
37
+ Difference,
38
+ Plan,
39
+ SingleEntityPlanner,
40
+ diff,
41
+ )
42
+
43
+ __all__ = [
44
+ "ADAPTERS",
45
+ "FIELD_POLICIES",
46
+ "ApplyError",
47
+ "ApplyResult",
48
+ "BulkCreateReport",
49
+ "BulkCreator",
50
+ "CannotCompare",
51
+ "CreatedEntity",
52
+ "DependencyGraph",
53
+ "Difference",
54
+ "EnvCredentialResolver",
55
+ "FailedEntity",
56
+ "FieldError",
57
+ "FieldPolicy",
58
+ "KindAdapter",
59
+ "NameLookup",
60
+ "Plan",
61
+ "PlatformRejectionError",
62
+ "SecretValue",
63
+ "SingleEntityPlanner",
64
+ "UnresolvableCredentialError",
65
+ "UnresolvedReferenceError",
66
+ "adapter_for",
67
+ "diff",
68
+ "guard_datasource_identity",
69
+ "guard_supported",
70
+ ]