prizmkit 1.1.166 → 1.1.169

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.
@@ -1,10 +1,9 @@
1
1
  #!/usr/bin/env python3
2
- """Validate non-sensitive semantic invariants for PrizmKit Deploy artifacts.
2
+ """Validate PrizmKit Deploy v2 artifacts through one deterministic entry point.
3
3
 
4
- This companion validator is intentionally read-only and standard-library-only.
5
- JSON Schema validation remains mandatory; this script enforces cross-field and
6
- host-neutral path rules that are awkward to express or easy to regress in a
7
- schema alone. Diagnostics contain stable codes and JSON paths, never values.
4
+ This read-only standard-library validator loads the shipped JSON Schema, checks its
5
+ structural subset and cross-field rules, binds Profile records to their filenames,
6
+ and emits only bounded stable codes plus JSON paths.
8
7
  """
9
8
 
10
9
  from __future__ import annotations
@@ -21,12 +20,40 @@ from typing import Any, Iterable, Mapping, Sequence
21
20
 
22
21
  MAX_INPUT_BYTES = 1024 * 1024
23
22
  MAX_ERRORS = 50
24
- VERIFICATION_LAYERS = {
25
- "command_or_platform",
26
- "runtime_or_release",
27
- "configured_health",
28
- "external_url",
29
- "startup_logs",
23
+ SUPPORTED_SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema"
24
+ SCHEMA_FILES = {
25
+ "declaration": "deployment-declaration-schema.json",
26
+ "record": "deploy-record-schema.json",
27
+ }
28
+ SUPPORTED_SCHEMA_KEYWORDS = {
29
+ "$defs",
30
+ "$id",
31
+ "$ref",
32
+ "$schema",
33
+ "additionalProperties",
34
+ "allOf",
35
+ "const",
36
+ "contains",
37
+ "description",
38
+ "else",
39
+ "enum",
40
+ "if",
41
+ "items",
42
+ "maxItems",
43
+ "maxLength",
44
+ "maximum",
45
+ "minItems",
46
+ "minLength",
47
+ "minimum",
48
+ "not",
49
+ "oneOf",
50
+ "pattern",
51
+ "properties",
52
+ "required",
53
+ "then",
54
+ "title",
55
+ "type",
56
+ "uniqueItems",
30
57
  }
31
58
  FORBIDDEN_FIELDS = {
32
59
  "value",
@@ -43,7 +70,7 @@ _DRIVE_PREFIX = re.compile(r"^[A-Za-z]:")
43
70
 
44
71
 
45
72
  class DuplicateKeyError(ValueError):
46
- """Raised for a duplicate object key without retaining its key or value."""
73
+ """Raised for a duplicate object key without retaining its content."""
47
74
 
48
75
 
49
76
  @dataclass(frozen=True, order=True)
@@ -62,9 +89,12 @@ class ErrorCollector:
62
89
  self._errors: set[ValidationError] = set()
63
90
 
64
91
  def add(self, code: str, path: str) -> None:
65
- if len(self._errors) >= MAX_ERRORS:
66
- return
67
- self._errors.add(ValidationError(code=code, path=path))
92
+ if len(self._errors) < MAX_ERRORS:
93
+ self._errors.add(ValidationError(code=code, path=path))
94
+
95
+ @property
96
+ def full(self) -> bool:
97
+ return len(self._errors) >= MAX_ERRORS
68
98
 
69
99
  def result(self) -> list[dict[str, str]]:
70
100
  return [error.as_dict() for error in sorted(self._errors)]
@@ -79,6 +109,10 @@ def _strict_object(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
79
109
  return result
80
110
 
81
111
 
112
+ def _reject_json_constant(_value: str) -> None:
113
+ raise ValueError("non-standard JSON constant")
114
+
115
+
82
116
  def _load_json(path: Path) -> tuple[Any | None, list[dict[str, str]]]:
83
117
  try:
84
118
  metadata = path.lstat()
@@ -90,51 +124,328 @@ def _load_json(path: Path) -> tuple[Any | None, list[dict[str, str]]]:
90
124
  return None, [{"code": "INPUT_TOO_LARGE", "path": "$"}]
91
125
  try:
92
126
  content = path.read_text(encoding="utf-8")
93
- return json.loads(content, object_pairs_hook=_strict_object), []
127
+ return json.loads(
128
+ content,
129
+ object_pairs_hook=_strict_object,
130
+ parse_constant=_reject_json_constant,
131
+ ), []
94
132
  except DuplicateKeyError:
95
133
  return None, [{"code": "DUPLICATE_KEY", "path": "$"}]
96
- except (OSError, UnicodeError, json.JSONDecodeError, RecursionError):
134
+ except (OSError, UnicodeError, ValueError, RecursionError):
97
135
  return None, [{"code": "INVALID_JSON", "path": "$"}]
98
136
 
99
137
 
100
- def _is_project_relative_path(value: Any, *, allow_root: bool = False) -> bool:
101
- if not isinstance(value, str) or not value or len(value) > 512:
102
- return False
103
- if value == ".":
104
- return allow_root
105
- if value.startswith("/") or _DRIVE_PREFIX.match(value) or "\\" in value:
106
- return False
107
- if any(unicodedata.category(character) in {"Cc", "Cs"} for character in value):
108
- return False
109
- parts = value.split("/")
110
- return all(part not in {"", ".", ".."} for part in parts)
138
+ def _load_schema(kind: str) -> Mapping[str, Any] | None:
139
+ schema_path = (
140
+ Path(__file__).resolve().parent.parent / "references" / SCHEMA_FILES[kind]
141
+ )
142
+ schema, load_errors = _load_json(schema_path)
143
+ if load_errors or not isinstance(schema, Mapping):
144
+ return None
145
+ return schema
111
146
 
112
147
 
113
- def _is_legacy_deploy_path(value: Any) -> bool:
114
- return _is_project_relative_path(value) and str(value).startswith(".prizmkit/deploy/")
148
+ def _json_path(path: str, key: str) -> str:
149
+ return f"{path}.{key}" if _SAFE_KEY.fullmatch(key) else f"{path}.[unknown]"
115
150
 
116
151
 
117
- def _iter_list(value: Any) -> Iterable[tuple[int, Any]]:
118
- if not isinstance(value, list):
119
- return ()
120
- return enumerate(value)
152
+ def _json_equal(left: Any, right: Any) -> bool:
153
+ if isinstance(left, bool) or isinstance(right, bool):
154
+ return isinstance(left, bool) and isinstance(right, bool) and left == right
155
+ if isinstance(left, (int, float)) and isinstance(right, (int, float)):
156
+ return left == right
157
+ if isinstance(left, Mapping) and isinstance(right, Mapping):
158
+ return left.keys() == right.keys() and all(
159
+ _json_equal(left[key], right[key]) for key in left
160
+ )
161
+ if isinstance(left, list) and isinstance(right, list):
162
+ return len(left) == len(right) and all(
163
+ _json_equal(left_item, right_item)
164
+ for left_item, right_item in zip(left, right)
165
+ )
166
+ return type(left) is type(right) and left == right
167
+
168
+
169
+ def _matches_type(value: Any, expected: str) -> bool:
170
+ if expected == "null":
171
+ return value is None
172
+ if expected == "boolean":
173
+ return isinstance(value, bool)
174
+ if expected == "object":
175
+ return isinstance(value, Mapping)
176
+ if expected == "array":
177
+ return isinstance(value, list)
178
+ if expected == "string":
179
+ return isinstance(value, str)
180
+ if expected == "number":
181
+ return isinstance(value, (int, float)) and not isinstance(value, bool)
182
+ if expected == "integer":
183
+ integer = isinstance(value, int) and not isinstance(value, bool)
184
+ integral_number = isinstance(value, float) and value.is_integer()
185
+ return integer or integral_number
186
+ return False
187
+
188
+
189
+ def _resolve_local_ref(root: Mapping[str, Any], reference: Any) -> Mapping[str, Any]:
190
+ if not isinstance(reference, str) or not reference.startswith("#/"):
191
+ raise KeyError("unsupported schema reference")
192
+ current: Any = root
193
+ for encoded_part in reference[2:].split("/"):
194
+ part = encoded_part.replace("~1", "/").replace("~0", "~")
195
+ if not isinstance(current, Mapping) or part not in current:
196
+ raise KeyError("unresolved schema reference")
197
+ current = current[part]
198
+ if not isinstance(current, Mapping):
199
+ raise KeyError("schema reference is not an object")
200
+ return current
201
+
202
+
203
+ def _schema_contract_supported(
204
+ schema: Mapping[str, Any], root: Mapping[str, Any]
205
+ ) -> bool:
206
+ if any(key not in SUPPORTED_SCHEMA_KEYWORDS for key in schema):
207
+ return False
208
+ if "$ref" in schema:
209
+ try:
210
+ _resolve_local_ref(root, schema["$ref"])
211
+ except KeyError:
212
+ return False
213
+ for container_name in ("properties", "$defs"):
214
+ container = schema.get(container_name, {})
215
+ if not isinstance(container, Mapping) or any(
216
+ not isinstance(child, Mapping)
217
+ or not _schema_contract_supported(child, root)
218
+ for child in container.values()
219
+ ):
220
+ return False
221
+ for child_name in (
222
+ "additionalProperties",
223
+ "contains",
224
+ "else",
225
+ "if",
226
+ "items",
227
+ "not",
228
+ "then",
229
+ ):
230
+ child = schema.get(child_name)
231
+ if isinstance(child, Mapping) and not _schema_contract_supported(child, root):
232
+ return False
233
+ for children_name in ("allOf", "oneOf"):
234
+ children = schema.get(children_name)
235
+ if children is None:
236
+ continue
237
+ if not isinstance(children, list) or any(
238
+ not isinstance(child, Mapping)
239
+ or not _schema_contract_supported(child, root)
240
+ for child in children
241
+ ):
242
+ return False
243
+ return True
121
244
 
122
245
 
123
- def _check_path_list(
246
+ def _schema_matches(
124
247
  value: Any,
248
+ schema: Mapping[str, Any],
249
+ root: Mapping[str, Any],
125
250
  path: str,
126
251
  errors: ErrorCollector,
127
- *,
128
- legacy: bool = False,
129
- ) -> None:
130
- predicate = _is_legacy_deploy_path if legacy else _is_project_relative_path
252
+ ) -> bool:
253
+ """Evaluate the JSON Schema keywords used by the two shipped closed schemas."""
254
+ if errors.full:
255
+ return False
256
+ valid = True
257
+
258
+ if "$ref" in schema:
259
+ try:
260
+ referenced = _resolve_local_ref(root, schema["$ref"])
261
+ except KeyError:
262
+ errors.add("SCHEMA_CONTRACT_INVALID", "$schema")
263
+ return False
264
+ if not _schema_matches(value, referenced, root, path, errors):
265
+ valid = False
266
+
267
+ expected_types = schema.get("type")
268
+ if expected_types is not None:
269
+ if isinstance(expected_types, str):
270
+ expected_types = [expected_types]
271
+ if not isinstance(expected_types, list) or not any(
272
+ isinstance(expected, str) and _matches_type(value, expected)
273
+ for expected in expected_types
274
+ ):
275
+ errors.add("SCHEMA_TYPE", path)
276
+ return False
277
+
278
+ if "const" in schema and not _json_equal(value, schema["const"]):
279
+ errors.add("SCHEMA_CONST", path)
280
+ valid = False
281
+ if "enum" in schema and not any(
282
+ _json_equal(value, candidate) for candidate in schema["enum"]
283
+ ):
284
+ errors.add("SCHEMA_ENUM", path)
285
+ valid = False
286
+
287
+ if "oneOf" in schema:
288
+ branches = schema["oneOf"]
289
+ matches = 0
290
+ if isinstance(branches, list):
291
+ for branch in branches:
292
+ probe = ErrorCollector()
293
+ if isinstance(branch, Mapping) and _schema_matches(
294
+ value, branch, root, path, probe
295
+ ):
296
+ matches += 1
297
+ if matches != 1:
298
+ errors.add("SCHEMA_ONE_OF", path)
299
+ valid = False
300
+
301
+ for branch in schema.get("allOf", ()):
302
+ if not isinstance(branch, Mapping):
303
+ errors.add("SCHEMA_CONTRACT_INVALID", "$schema")
304
+ valid = False
305
+ elif not _schema_matches(value, branch, root, path, errors):
306
+ valid = False
307
+
308
+ condition = schema.get("if")
309
+ if isinstance(condition, Mapping):
310
+ probe = ErrorCollector()
311
+ selected = (
312
+ "then"
313
+ if _schema_matches(value, condition, root, path, probe)
314
+ else "else"
315
+ )
316
+ branch = schema.get(selected)
317
+ if isinstance(branch, Mapping) and not _schema_matches(
318
+ value, branch, root, path, errors
319
+ ):
320
+ valid = False
321
+
322
+ negated = schema.get("not")
323
+ if isinstance(negated, Mapping):
324
+ probe = ErrorCollector()
325
+ if _schema_matches(value, negated, root, path, probe):
326
+ errors.add("SCHEMA_NOT", path)
327
+ valid = False
328
+
329
+ contains = schema.get("contains")
330
+ if isinstance(value, list) and isinstance(contains, Mapping):
331
+ if not any(
332
+ _schema_matches(item, contains, root, f"{path}[{index}]", ErrorCollector())
333
+ for index, item in enumerate(value)
334
+ ):
335
+ errors.add("SCHEMA_CONTAINS", path)
336
+ valid = False
337
+
338
+ if isinstance(value, Mapping):
339
+ properties = schema.get("properties", {})
340
+ if not isinstance(properties, Mapping):
341
+ errors.add("SCHEMA_CONTRACT_INVALID", "$schema")
342
+ return False
343
+ required = schema.get("required", ())
344
+ if isinstance(required, list):
345
+ for key in required:
346
+ if isinstance(key, str) and key not in value:
347
+ errors.add("SCHEMA_REQUIRED", _json_path(path, key))
348
+ valid = False
349
+ for key, child in value.items():
350
+ child_schema = properties.get(key)
351
+ child_path = _json_path(path, str(key))
352
+ if isinstance(child_schema, Mapping):
353
+ if not _schema_matches(child, child_schema, root, child_path, errors):
354
+ valid = False
355
+ continue
356
+ additional = schema.get("additionalProperties", True)
357
+ if additional is False:
358
+ errors.add("SCHEMA_ADDITIONAL_PROPERTY", f"{path}.[unknown]")
359
+ valid = False
360
+ elif isinstance(additional, Mapping) and not _schema_matches(
361
+ child, additional, root, child_path, errors
362
+ ):
363
+ valid = False
364
+
365
+ if isinstance(value, list):
366
+ minimum_items = schema.get("minItems")
367
+ maximum_items = schema.get("maxItems")
368
+ if isinstance(minimum_items, int) and len(value) < minimum_items:
369
+ errors.add("SCHEMA_MIN_ITEMS", path)
370
+ valid = False
371
+ if isinstance(maximum_items, int) and len(value) > maximum_items:
372
+ errors.add("SCHEMA_MAX_ITEMS", path)
373
+ valid = False
374
+ if schema.get("uniqueItems") is True:
375
+ for index, item in enumerate(value):
376
+ if any(_json_equal(item, previous) for previous in value[:index]):
377
+ errors.add("SCHEMA_UNIQUE_ITEMS", f"{path}[{index}]")
378
+ valid = False
379
+ if errors.full:
380
+ break
381
+ item_schema = schema.get("items")
382
+ if isinstance(item_schema, Mapping):
383
+ for index, item in enumerate(value):
384
+ if errors.full:
385
+ valid = False
386
+ break
387
+ if not _schema_matches(
388
+ item, item_schema, root, f"{path}[{index}]", errors
389
+ ):
390
+ valid = False
391
+
392
+ if isinstance(value, str):
393
+ minimum_length = schema.get("minLength")
394
+ maximum_length = schema.get("maxLength")
395
+ if isinstance(minimum_length, int) and len(value) < minimum_length:
396
+ errors.add("SCHEMA_MIN_LENGTH", path)
397
+ valid = False
398
+ if isinstance(maximum_length, int) and len(value) > maximum_length:
399
+ errors.add("SCHEMA_MAX_LENGTH", path)
400
+ valid = False
401
+ pattern = schema.get("pattern")
402
+ if isinstance(pattern, str):
403
+ try:
404
+ matches = re.search(pattern, value) is not None
405
+ except re.error:
406
+ errors.add("SCHEMA_CONTRACT_INVALID", "$schema")
407
+ return False
408
+ if not matches:
409
+ errors.add("SCHEMA_PATTERN", path)
410
+ valid = False
411
+
412
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
413
+ minimum = schema.get("minimum")
414
+ maximum = schema.get("maximum")
415
+ if isinstance(minimum, (int, float)) and value < minimum:
416
+ errors.add("SCHEMA_MINIMUM", path)
417
+ valid = False
418
+ if isinstance(maximum, (int, float)) and value > maximum:
419
+ errors.add("SCHEMA_MAXIMUM", path)
420
+ valid = False
421
+
422
+ return valid
423
+
424
+
425
+ def _iter_list(value: Any) -> Iterable[tuple[int, Any]]:
426
+ if isinstance(value, list):
427
+ return enumerate(value)
428
+ return ()
429
+
430
+
431
+ def _is_project_relative_path(value: Any) -> bool:
432
+ if not isinstance(value, str) or not value or len(value) > 512:
433
+ return False
434
+ if value.startswith("/") or _DRIVE_PREFIX.match(value) or "\\" in value:
435
+ return False
436
+ if any(unicodedata.category(character) in {"Cc", "Cs"} for character in value):
437
+ return False
438
+ return all(part not in {"", ".", ".."} for part in value.split("/"))
439
+
440
+
441
+ def _check_path_list(value: Any, path: str, errors: ErrorCollector) -> None:
131
442
  for index, item in _iter_list(value):
132
- if not predicate(item):
443
+ if not _is_project_relative_path(item):
133
444
  errors.add("UNSAFE_MANAGED_PATH", f"{path}[{index}]")
134
445
 
135
446
 
136
- def _check_forbidden_fields(value: Any, path: str, errors: ErrorCollector) -> None:
137
- pending: list[tuple[Any, str]] = [(value, path)]
447
+ def _check_forbidden_fields(value: Any, errors: ErrorCollector) -> None:
448
+ pending: list[tuple[Any, str]] = [(value, "$")]
138
449
  while pending:
139
450
  current, current_path = pending.pop()
140
451
  if isinstance(current, Mapping):
@@ -154,7 +465,18 @@ def _check_forbidden_fields(value: Any, path: str, errors: ErrorCollector) -> No
154
465
  )
155
466
 
156
467
 
157
- def _check_unique_names(
468
+ def _check_profile_file_identity(
469
+ value: Any, input_path: Path, errors: ErrorCollector
470
+ ) -> None:
471
+ if not isinstance(value, Mapping):
472
+ return
473
+ profile = value.get("profile")
474
+ profile_id = profile.get("id") if isinstance(profile, Mapping) else None
475
+ if isinstance(profile_id, str) and input_path.name != f"{profile_id}.json":
476
+ errors.add("PROFILE_FILE_ID_MISMATCH", "$.profile.id")
477
+
478
+
479
+ def _unique_identities(
158
480
  value: Any,
159
481
  path: str,
160
482
  field: str,
@@ -174,44 +496,35 @@ def _check_unique_names(
174
496
  return seen
175
497
 
176
498
 
177
- def _check_profile_reference(
178
- value: Any,
179
- path: str,
180
- profiles: set[str],
181
- errors: ErrorCollector,
182
- ) -> None:
183
- if value is not None and isinstance(value, str) and value not in profiles:
184
- errors.add("DANGLING_PROFILE_REFERENCE", path)
185
-
186
-
187
- def _check_terminal_result(value: Any, path: str, errors: ErrorCollector) -> None:
499
+ def _check_result(value: Any, path: str, errors: ErrorCollector) -> None:
188
500
  if not isinstance(value, Mapping):
189
501
  return
190
502
  verification = value.get("verification")
191
- if not isinstance(verification, list):
192
- errors.add("VERIFICATION_LAYER_SET", f"{path}.verification")
193
- return
503
+ names = _unique_identities(
504
+ verification,
505
+ f"{path}.verification",
506
+ "name",
507
+ "DUPLICATE_VERIFICATION_OBSERVATION",
508
+ errors,
509
+ )
510
+ if isinstance(verification, list) and not names:
511
+ errors.add("EMPTY_VERIFICATION", f"{path}.verification")
194
512
 
195
- layers: list[str] = []
196
- for item in verification:
197
- if isinstance(item, Mapping) and isinstance(item.get("layer"), str):
198
- layers.append(item["layer"])
199
- if len(verification) != len(VERIFICATION_LAYERS) or set(layers) != VERIFICATION_LAYERS:
200
- errors.add("VERIFICATION_LAYER_SET", f"{path}.verification")
201
- if len(layers) != len(set(layers)):
202
- errors.add("DUPLICATE_VERIFICATION_LAYER", f"{path}.verification")
203
-
204
- if value.get("status") == "SUCCEEDED":
205
- for index, item in _iter_list(verification):
206
- if (
207
- isinstance(item, Mapping)
208
- and item.get("required") is True
209
- and item.get("status") != "PASSED"
210
- ):
211
- errors.add(
212
- "SUCCEEDED_REQUIRED_LAYER_NOT_PASSED",
213
- f"{path}.verification[{index}]",
214
- )
513
+ if value.get("status") != "SUCCEEDED":
514
+ return
515
+ for index, item in _iter_list(verification):
516
+ if (
517
+ isinstance(item, Mapping)
518
+ and item.get("required") is True
519
+ and item.get("status") != "PASSED"
520
+ ):
521
+ errors.add(
522
+ "SUCCEEDED_REQUIRED_OBSERVATION_NOT_PASSED",
523
+ f"{path}.verification[{index}]",
524
+ )
525
+ desired = value.get("desired_release")
526
+ if desired is not None and value.get("live_release") != desired:
527
+ errors.add("SUCCEEDED_RELEASE_MISMATCH", f"{path}.live_release")
215
528
 
216
529
 
217
530
  def _validate_record(data: Any, errors: ErrorCollector) -> None:
@@ -219,87 +532,43 @@ def _validate_record(data: Any, errors: ErrorCollector) -> None:
219
532
  errors.add("ROOT_NOT_OBJECT", "$")
220
533
  return
221
534
 
222
- project = data.get("project")
223
- if isinstance(project, Mapping):
224
- _check_path_list(
225
- project.get("native_config_files"),
226
- "$.project.native_config_files",
227
- errors,
228
- )
229
-
230
- profiles_value = data.get("profiles")
231
- profiles = _check_unique_names(
232
- profiles_value,
233
- "$.profiles",
234
- "id",
235
- "DUPLICATE_PROFILE_ID",
236
- errors,
237
- )
238
- for index, profile in _iter_list(profiles_value):
239
- if isinstance(profile, Mapping):
240
- _check_path_list(
241
- profile.get("native_config_files"),
242
- f"$.profiles[{index}].native_config_files",
243
- errors,
244
- )
245
-
246
- _check_unique_names(
535
+ _unique_identities(
247
536
  data.get("secret_references"),
248
537
  "$.secret_references",
249
538
  "name",
250
539
  "DUPLICATE_SECRET_REFERENCE",
251
540
  errors,
252
541
  )
253
-
254
- current = data.get("current")
255
- if isinstance(current, Mapping):
256
- _check_profile_reference(
257
- current.get("profile_id"),
258
- "$.current.profile_id",
259
- profiles,
260
- errors,
261
- )
262
-
263
542
  latest = data.get("latest_result")
264
- if isinstance(latest, Mapping):
265
- _check_profile_reference(
266
- latest.get("profile_id"),
267
- "$.latest_result.profile_id",
268
- profiles,
269
- errors,
270
- )
271
- _check_terminal_result(latest, "$.latest_result", errors)
272
-
273
- for index, history in _iter_list(data.get("history")):
274
- if isinstance(history, Mapping):
275
- _check_profile_reference(
276
- history.get("profile_id"),
277
- f"$.history[{index}].profile_id",
278
- profiles,
279
- errors,
280
- )
543
+ _check_result(latest, "$.latest_result", errors)
281
544
 
282
545
  recovery = data.get("recovery")
283
- if isinstance(recovery, Mapping):
284
- _check_profile_reference(
285
- recovery.get("profile_id"),
286
- "$.recovery.profile_id",
287
- profiles,
288
- errors,
289
- )
546
+ if not isinstance(latest, Mapping) and recovery is not None:
547
+ errors.add("ORPHAN_RECOVERY", "$.recovery")
548
+ if isinstance(latest, Mapping):
549
+ status = latest.get("status")
550
+ if status == "WAITING_USER" and not isinstance(recovery, Mapping):
551
+ errors.add("WAITING_USER_RECOVERY_REQUIRED", "$.recovery")
552
+ if status in {"SUCCEEDED", "FAILED"} and recovery is not None:
553
+ errors.add("TERMINAL_RECOVERY_FORBIDDEN", "$.recovery")
554
+ if status == "WAITING_USER" and isinstance(recovery, Mapping):
555
+ if recovery.get("operation") != latest.get("operation"):
556
+ errors.add("RECOVERY_OPERATION_MISMATCH", "$.recovery.operation")
557
+ if recovery.get("desired_release") != latest.get("desired_release"):
558
+ errors.add(
559
+ "RECOVERY_DESIRED_RELEASE_MISMATCH",
560
+ "$.recovery.desired_release",
561
+ )
290
562
 
291
- legacy = data.get("legacy_migration")
292
- if isinstance(legacy, Mapping):
293
- sources = legacy.get("sources")
294
- for index, source in _iter_list(sources):
295
- if isinstance(source, Mapping) and not _is_legacy_deploy_path(source.get("path")):
296
- errors.add("UNSAFE_MANAGED_PATH", f"$.legacy_migration.sources[{index}].path")
297
- _check_path_list(
298
- legacy.get("preserved_paths"),
299
- "$.legacy_migration.preserved_paths",
300
- errors,
301
- legacy=True,
302
- )
563
+ current = data.get("current")
564
+ if (
565
+ isinstance(latest, Mapping)
566
+ and latest.get("status") == "SUCCEEDED"
567
+ and isinstance(current, Mapping)
568
+ and latest.get("desired_release") is not None
569
+ and current.get("release_identity") != latest.get("desired_release")
570
+ ):
571
+ errors.add("CURRENT_RELEASE_MISMATCH", "$.current.release_identity")
303
572
 
304
573
 
305
574
  def _validate_declaration(data: Any, errors: ErrorCollector) -> None:
@@ -308,14 +577,26 @@ def _validate_declaration(data: Any, errors: ErrorCollector) -> None:
308
577
  return
309
578
 
310
579
  _check_path_list(data.get("native_config_files"), "$.native_config_files", errors)
311
- _check_unique_names(
312
- data.get("profile_hints"),
313
- "$.profile_hints",
580
+ profiles_value = data.get("profiles")
581
+ profiles = _unique_identities(
582
+ profiles_value,
583
+ "$.profiles",
314
584
  "id",
315
585
  "DUPLICATE_PROFILE_ID",
316
586
  errors,
317
587
  )
318
- _check_unique_names(
588
+ for index, profile in _iter_list(profiles_value):
589
+ if isinstance(profile, Mapping):
590
+ _check_path_list(
591
+ profile.get("native_config_files"),
592
+ f"$.profiles[{index}].native_config_files",
593
+ errors,
594
+ )
595
+ default_profile = data.get("default_profile")
596
+ if isinstance(default_profile, str) and default_profile not in profiles:
597
+ errors.add("DANGLING_DEFAULT_PROFILE", "$.default_profile")
598
+
599
+ _unique_identities(
319
600
  data.get("secret_references"),
320
601
  "$.secret_references",
321
602
  "name",
@@ -323,26 +604,18 @@ def _validate_declaration(data: Any, errors: ErrorCollector) -> None:
323
604
  errors,
324
605
  )
325
606
 
326
- for index, command in _iter_list(data.get("commands")):
327
- if (
328
- isinstance(command, Mapping)
329
- and not _is_project_relative_path(command.get("working_directory"), allow_root=True)
330
- ):
331
- errors.add("UNSAFE_MANAGED_PATH", f"$.commands[{index}].working_directory")
332
-
333
- for index, hint in _iter_list(data.get("capability_hints")):
334
- if isinstance(hint, Mapping):
335
- _check_path_list(
336
- hint.get("evidence_files"),
337
- f"$.capability_hints[{index}].evidence_files",
338
- errors,
339
- )
340
-
341
607
 
342
- def validate(kind: str, data: Any) -> list[dict[str, str]]:
608
+ def validate(
609
+ kind: str,
610
+ data: Any,
611
+ input_path: Path,
612
+ schema: Mapping[str, Any],
613
+ ) -> list[dict[str, str]]:
343
614
  errors = ErrorCollector()
344
- _check_forbidden_fields(data, "$", errors)
615
+ _schema_matches(data, schema, schema, "$", errors)
616
+ _check_forbidden_fields(data, errors)
345
617
  if kind == "record":
618
+ _check_profile_file_identity(data, input_path, errors)
346
619
  _validate_record(data, errors)
347
620
  else:
348
621
  _validate_declaration(data, errors)
@@ -351,7 +624,7 @@ def validate(kind: str, data: Any) -> list[dict[str, str]]:
351
624
 
352
625
  def _parser() -> argparse.ArgumentParser:
353
626
  parser = argparse.ArgumentParser(
354
- description="Validate semantic invariants for one PrizmKit Deploy artifact."
627
+ description="Validate one PrizmKit Deploy v2 artifact completely."
355
628
  )
356
629
  parser.add_argument("--kind", choices=("record", "declaration"), required=True)
357
630
  parser.add_argument("path", type=Path)
@@ -361,9 +634,25 @@ def _parser() -> argparse.ArgumentParser:
361
634
  def main(argv: Sequence[str] | None = None) -> int:
362
635
  args = _parser().parse_args(argv)
363
636
  data, load_errors = _load_json(args.path)
364
- errors = load_errors or validate(args.kind, data)
365
- output = {"valid": not errors, "errors": errors}
366
- print(json.dumps(output, ensure_ascii=False, separators=(",", ":")))
637
+ schema = _load_schema(args.kind)
638
+ if load_errors:
639
+ errors = load_errors
640
+ elif schema is None:
641
+ errors = [{"code": "SCHEMA_CONTRACT_UNAVAILABLE", "path": "$schema"}]
642
+ elif (
643
+ schema.get("$schema") != SUPPORTED_SCHEMA_DIALECT
644
+ or not _schema_contract_supported(schema, schema)
645
+ ):
646
+ errors = [{"code": "SCHEMA_CONTRACT_UNSUPPORTED", "path": "$schema"}]
647
+ else:
648
+ errors = validate(args.kind, data, args.path, schema)
649
+ print(
650
+ json.dumps(
651
+ {"valid": not errors, "errors": errors},
652
+ ensure_ascii=False,
653
+ separators=(",", ":"),
654
+ )
655
+ )
367
656
  return 0 if not errors else 1
368
657
 
369
658