prizmkit 1.1.167 → 1.1.170

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.
@@ -10,14 +10,16 @@ An explicit deploy invocation authorizes the selected Profile's standard deploym
10
10
 
11
11
  The standard envelope covers project-owned, bounded actions needed to build/package, resolve project-declared dependencies, apply non-destructive native migrations, create a candidate, start/restart, hand off live traffic, verify, retain bounded rollback, retire exact old runtime resources, clean failed/temporary resources, and update the selected Profile record.
12
12
 
13
- Pause with one exact `WAITING_USER` action only for:
13
+ For a selected directly managed remote machine, connecting and running bounded project-scoped actions through the established SSH destination are part of that standard envelope. Do not ask for another confirmation merely because the next executable is `ssh`; use established non-interactive credentials first. A missing Profile record or ordinary first deployment also does not create a checkpoint when one non-conflicting target resolves from current evidence.
14
14
 
15
- 1. an identity or authentication action that only the user can complete;
16
- 2. a target choice current evidence cannot resolve;
15
+ Exhaust bounded automatic discovery, target resolution, and configured non-interactive authentication before pausing with one exact `WAITING_USER` action. Pause only for:
16
+
17
+ 1. an identity or authentication action that only the user can complete after established methods have been attempted;
18
+ 2. a target choice still absent, ambiguous, or conflicting after current evidence is inspected;
17
19
  3. an irreversible data effect or data impact that cannot be bounded safely;
18
20
  4. a shared or unknown-ownership resource decision.
19
21
 
20
- A missing reliable rollback is disclosed but does not create another approval. Privileged/global work not already established by the selected target boundary is treated as an authorization or shared-ownership decision rather than silently executed.
22
+ Known bounded downtime, material work inside the standard envelope, and missing reliable rollback are disclosed while execution continues; they do not create another approval. Privileged/global work not already established by the selected target boundary is treated as an authorization or shared-ownership decision rather than silently executed.
21
23
 
22
24
  ## Effect and Resource Policy
23
25
 
@@ -35,6 +37,12 @@ A material budget covers aggregate attempts rather than resetting per retry. Est
35
37
 
36
38
  Do not run a material producer when current project-native evidence already covers the same source/release, toolchain, target assumptions, and required scope. Run the least expensive missing producer at most once for that binding. A changed binding starts a newly observed current→desired decision; it does not justify automatic repeated full rings.
37
39
 
40
+ ## SSH Execution Boundary
41
+
42
+ For each selected SSH action, preserve the verified destination, authentication identity, proxy path, host-key evidence, and project-owned working boundary used during discovery. Execute the smallest exact remote command needed for the current difference, with bounded connection/action time and output. Reuse one proven connection binding across observation, transfer, write, and verification instead of silently changing users or endpoints between steps.
43
+
44
+ Do not pass Secret values in command arguments, print private-key material, start a broad remote inventory, or bypass host-key verification. Attempt one bounded non-interactive connection with the established SSH configuration before deciding authentication cannot complete; continue immediately when it succeeds. Only then return one exact `WAITING_USER` authentication action when user input is unavoidable. If the target key or destination differs from established evidence, treat it as an identity conflict rather than a transient retry. After a disconnect during a possible write, use the same verified SSH destination to inspect actual state before considering replay.
45
+
38
46
  ## Current → Desired Loop
39
47
 
40
48
  For one selected Profile:
@@ -90,9 +90,11 @@ After timeout, disconnect, or interruption during a possible write:
90
90
 
91
91
  Never infer “not applied” from a missing response. Never rerun a material producer merely to reconstruct history.
92
92
 
93
+ For a directly managed remote machine, reconnect through the same verified SSH destination and authentication identity used for the action. A successful SSH connection proves access only; it does not prove that the desired release, runtime, selector, health, or cleanup postconditions succeeded. An unexpected host key or destination is an identity conflict, not evidence that the write was unapplied.
94
+
93
95
  ## Interruption and Resume
94
96
 
95
- Load only the selected Profile record's current, latest result, minimal recovery, and bounded observations. Then rediscover project revision, target fingerprint, authentication identity, desired release eligibility, actual live/candidate inventory, selector, owned residuals, configured health, and relevant tool capability.
97
+ Load only the selected Profile record's current, latest result, minimal recovery, and bounded observations. Then rediscover project revision, target fingerprint, connection transport and destination, authentication identity, desired release eligibility, actual live/candidate inventory, selector, owned residuals, configured health, and relevant tool capability. For a directly managed remote machine, re-establish the same verified SSH binding before inspecting or resuming target actions.
96
98
 
97
99
  Resume from the first unproven current→desired action. Do not reconstruct commands from history summaries. When observed identity/effects differ, discard the stale proposed action and derive the next action from current evidence. If another operation already targets the same Profile/desired release, attach to it rather than creating a candidate.
98
100
 
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env python3
2
- """Validate non-sensitive semantic invariants for PrizmKit Deploy v2 artifacts.
2
+ """Validate PrizmKit Deploy v2 artifacts through one deterministic entry point.
3
3
 
4
- JSON Schema validation remains mandatory. This read-only standard-library companion
5
- checks cross-field rules and emits only bounded stable codes plus JSON paths.
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.
6
7
  """
7
8
 
8
9
  from __future__ import annotations
@@ -19,6 +20,41 @@ from typing import Any, Iterable, Mapping, Sequence
19
20
 
20
21
  MAX_INPUT_BYTES = 1024 * 1024
21
22
  MAX_ERRORS = 50
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",
57
+ }
22
58
  FORBIDDEN_FIELDS = {
23
59
  "value",
24
60
  "secret_value",
@@ -56,6 +92,10 @@ class ErrorCollector:
56
92
  if len(self._errors) < MAX_ERRORS:
57
93
  self._errors.add(ValidationError(code=code, path=path))
58
94
 
95
+ @property
96
+ def full(self) -> bool:
97
+ return len(self._errors) >= MAX_ERRORS
98
+
59
99
  def result(self) -> list[dict[str, str]]:
60
100
  return [error.as_dict() for error in sorted(self._errors)]
61
101
 
@@ -69,6 +109,10 @@ def _strict_object(pairs: Sequence[tuple[str, Any]]) -> dict[str, Any]:
69
109
  return result
70
110
 
71
111
 
112
+ def _reject_json_constant(_value: str) -> None:
113
+ raise ValueError("non-standard JSON constant")
114
+
115
+
72
116
  def _load_json(path: Path) -> tuple[Any | None, list[dict[str, str]]]:
73
117
  try:
74
118
  metadata = path.lstat()
@@ -80,13 +124,304 @@ def _load_json(path: Path) -> tuple[Any | None, list[dict[str, str]]]:
80
124
  return None, [{"code": "INPUT_TOO_LARGE", "path": "$"}]
81
125
  try:
82
126
  content = path.read_text(encoding="utf-8")
83
- 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
+ ), []
84
132
  except DuplicateKeyError:
85
133
  return None, [{"code": "DUPLICATE_KEY", "path": "$"}]
86
- except (OSError, UnicodeError, json.JSONDecodeError, RecursionError):
134
+ except (OSError, UnicodeError, ValueError, RecursionError):
87
135
  return None, [{"code": "INVALID_JSON", "path": "$"}]
88
136
 
89
137
 
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
146
+
147
+
148
+ def _json_path(path: str, key: str) -> str:
149
+ return f"{path}.{key}" if _SAFE_KEY.fullmatch(key) else f"{path}.[unknown]"
150
+
151
+
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
244
+
245
+
246
+ def _schema_matches(
247
+ value: Any,
248
+ schema: Mapping[str, Any],
249
+ root: Mapping[str, Any],
250
+ path: str,
251
+ errors: ErrorCollector,
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
+
90
425
  def _iter_list(value: Any) -> Iterable[tuple[int, Any]]:
91
426
  if isinstance(value, list):
92
427
  return enumerate(value)
@@ -130,6 +465,17 @@ def _check_forbidden_fields(value: Any, errors: ErrorCollector) -> None:
130
465
  )
131
466
 
132
467
 
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
+
133
479
  def _unique_identities(
134
480
  value: Any,
135
481
  path: str,
@@ -259,10 +605,17 @@ def _validate_declaration(data: Any, errors: ErrorCollector) -> None:
259
605
  )
260
606
 
261
607
 
262
- 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]]:
263
614
  errors = ErrorCollector()
615
+ _schema_matches(data, schema, schema, "$", errors)
264
616
  _check_forbidden_fields(data, errors)
265
617
  if kind == "record":
618
+ _check_profile_file_identity(data, input_path, errors)
266
619
  _validate_record(data, errors)
267
620
  else:
268
621
  _validate_declaration(data, errors)
@@ -271,7 +624,7 @@ def validate(kind: str, data: Any) -> list[dict[str, str]]:
271
624
 
272
625
  def _parser() -> argparse.ArgumentParser:
273
626
  parser = argparse.ArgumentParser(
274
- description="Validate semantic invariants for one PrizmKit Deploy v2 artifact."
627
+ description="Validate one PrizmKit Deploy v2 artifact completely."
275
628
  )
276
629
  parser.add_argument("--kind", choices=("record", "declaration"), required=True)
277
630
  parser.add_argument("path", type=Path)
@@ -281,7 +634,18 @@ def _parser() -> argparse.ArgumentParser:
281
634
  def main(argv: Sequence[str] | None = None) -> int:
282
635
  args = _parser().parse_args(argv)
283
636
  data, load_errors = _load_json(args.path)
284
- errors = load_errors or validate(args.kind, data)
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)
285
649
  print(
286
650
  json.dumps(
287
651
  {"valid": not errors, "errors": errors},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prizmkit",
3
- "version": "1.1.167",
3
+ "version": "1.1.170",
4
4
  "description": "Create a new PrizmKit-powered project with clean initialization — no framework dev files, just what you need.",
5
5
  "type": "module",
6
6
  "bin": {