loft-cli-core 0.6.3__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 (41) hide show
  1. loft_cli_core/__init__.py +1 -0
  2. loft_cli_core/agent_models.py +34 -0
  3. loft_cli_core/agent_paths.py +27 -0
  4. loft_cli_core/plan/__init__.py +0 -0
  5. loft_cli_core/plan/models.py +80 -0
  6. loft_cli_core/plan/render_diff.py +112 -0
  7. loft_cli_core/plan/render_markdown.py +189 -0
  8. loft_cli_core/plan/render_text.py +86 -0
  9. loft_cli_core/policy.py +218 -0
  10. loft_cli_core/registry/__init__.py +108 -0
  11. loft_cli_core/registry/executors.py +31 -0
  12. loft_cli_core/registry/hooks.py +46 -0
  13. loft_cli_core/registry/local_paths.py +147 -0
  14. loft_cli_core/registry/normalizers.py +21 -0
  15. loft_cli_core/registry/planners.py +21 -0
  16. loft_cli_core/registry/resolvers.py +65 -0
  17. loft_cli_core/registry/specs.py +20 -0
  18. loft_cli_core/registry/validators.py +21 -0
  19. loft_cli_core/specs/__init__.py +0 -0
  20. loft_cli_core/specs/backup_job_schema.py +95 -0
  21. loft_cli_core/specs/bootstrap_schema.py +124 -0
  22. loft_cli_core/specs/compose_project_schema.py +93 -0
  23. loft_cli_core/specs/file_template_schema.py +64 -0
  24. loft_cli_core/specs/http_check_schema.py +64 -0
  25. loft_cli_core/specs/loader.py +250 -0
  26. loft_cli_core/specs/postgres_ensure_schema.py +104 -0
  27. loft_cli_core/specs/service_schema.py +114 -0
  28. loft_cli_core/specs/stack_schema.py +74 -0
  29. loft_cli_core/specs/systemd_timer_schema.py +76 -0
  30. loft_cli_core/specs/systemd_unit_schema.py +86 -0
  31. loft_cli_core/specs/validators.py +755 -0
  32. loft_cli_core/state.py +31 -0
  33. loft_cli_core/utils/__init__.py +0 -0
  34. loft_cli_core/utils/files.py +41 -0
  35. loft_cli_core/utils/hashing.py +10 -0
  36. loft_cli_core/utils/os_detect.py +36 -0
  37. loft_cli_core/utils/templates.py +87 -0
  38. loft_cli_core-0.6.3.dist-info/METADATA +10 -0
  39. loft_cli_core-0.6.3.dist-info/RECORD +41 -0
  40. loft_cli_core-0.6.3.dist-info/WHEEL +5 -0
  41. loft_cli_core-0.6.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,755 @@
1
+ """Cross-field validation beyond Pydantic schema checks."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from dataclasses import dataclass
7
+ from typing import Literal
8
+
9
+ from loft_cli_core.specs.backup_job_schema import BackupJobSpec
10
+ from loft_cli_core.specs.bootstrap_schema import BootstrapSpec
11
+ from loft_cli_core.specs.compose_project_schema import ComposeProjectSpec
12
+ from loft_cli_core.specs.file_template_schema import FileTemplateSpec
13
+ from loft_cli_core.specs.http_check_schema import HttpCheckSpec
14
+ from loft_cli_core.specs.postgres_ensure_schema import PostgresEnsureSpec
15
+ from loft_cli_core.specs.service_schema import ServiceSpec
16
+ from loft_cli_core.specs.stack_schema import StackSpec
17
+ from loft_cli_core.specs.systemd_timer_schema import SystemdTimerSpec
18
+ from loft_cli_core.specs.systemd_unit_schema import SystemdUnitSpec
19
+
20
+ AnySpec = (
21
+ BootstrapSpec
22
+ | ServiceSpec
23
+ | FileTemplateSpec
24
+ | ComposeProjectSpec
25
+ | StackSpec
26
+ | HttpCheckSpec
27
+ | SystemdUnitSpec
28
+ | SystemdTimerSpec
29
+ | BackupJobSpec
30
+ | PostgresEnsureSpec
31
+ )
32
+
33
+
34
+ @dataclass
35
+ class ValidationIssue:
36
+ severity: Literal["error", "warning"]
37
+ field: str
38
+ message: str
39
+
40
+ def __str__(self) -> str:
41
+ icon = "✗" if self.severity == "error" else "⚠"
42
+ return f"{icon} [{self.severity.upper()}] {self.field}: {self.message}"
43
+
44
+
45
+ def validate_bootstrap(spec: BootstrapSpec) -> list[ValidationIssue]:
46
+ issues: list[ValidationIssue] = []
47
+
48
+ # SSH port range
49
+ if not (1 <= spec.ssh.port <= 65535):
50
+ issues.append(
51
+ ValidationIssue(
52
+ "error",
53
+ "ssh.port",
54
+ f"Port {spec.ssh.port} is out of valid range 1-65535",
55
+ )
56
+ )
57
+
58
+ # disable_password_auth requires at least one pubkey
59
+ if spec.ssh.disable_password_auth and not spec.admin_user.pubkeys:
60
+ issues.append(
61
+ ValidationIssue(
62
+ "error",
63
+ "ssh.disable_password_auth",
64
+ "disable_password_auth=true requires at least one pubkey in admin_user.pubkeys",
65
+ )
66
+ )
67
+
68
+ # WireGuard completeness
69
+ wg = spec.wireguard
70
+ if wg.enabled:
71
+ for attr, label in [
72
+ ("endpoint", "wireguard.endpoint"),
73
+ ("address", "wireguard.address"),
74
+ ("peer_address", "wireguard.peer_address"),
75
+ ]:
76
+ if not getattr(wg, attr):
77
+ issues.append(
78
+ ValidationIssue(
79
+ "error",
80
+ label,
81
+ f"wireguard.enabled=true requires {label} to be set",
82
+ )
83
+ )
84
+
85
+ # registered_peers_only requires WireGuard
86
+ if spec.firewall.registered_peers_only and not spec.wireguard.enabled:
87
+ issues.append(
88
+ ValidationIssue(
89
+ "warning",
90
+ "firewall.registered_peers_only",
91
+ "registered_peers_only=true has no effect when wireguard.enabled=false",
92
+ )
93
+ )
94
+
95
+ # SSH port should differ from login port
96
+ if spec.ssh.port == spec.login.port:
97
+ issues.append(
98
+ ValidationIssue(
99
+ "warning",
100
+ "ssh.port",
101
+ f"ssh.port ({spec.ssh.port}) is the same as login.port — "
102
+ "consider using a different port for post-bootstrap access",
103
+ )
104
+ )
105
+
106
+ # OS family check
107
+ if spec.host.os_family not in ("debian", "ubuntu"):
108
+ issues.append(
109
+ ValidationIssue(
110
+ "warning",
111
+ "host.os_family",
112
+ f"os_family '{spec.host.os_family}' may not be fully supported; "
113
+ "loft-cli V1 targets Debian/Ubuntu",
114
+ )
115
+ )
116
+
117
+ return issues
118
+
119
+
120
+ def validate_service(spec: ServiceSpec) -> list[ValidationIssue]:
121
+ issues: list[ValidationIssue] = []
122
+
123
+ # Postgres role password env
124
+ if spec.postgres and spec.postgres.create_role:
125
+ role = spec.postgres.create_role
126
+ if not role.password_env:
127
+ issues.append(
128
+ ValidationIssue(
129
+ "warning",
130
+ "postgres.create_role.password_env",
131
+ "No password_env set for postgres role — role will be created without password",
132
+ )
133
+ )
134
+
135
+ # Container images
136
+ for i, c in enumerate(spec.containers):
137
+ if not c.image:
138
+ issues.append(
139
+ ValidationIssue(
140
+ "error",
141
+ f"containers[{i}].image",
142
+ f"Container '{c.name}' has no image specified",
143
+ )
144
+ )
145
+
146
+ # Docker required for containers
147
+ if spec.containers and (spec.docker is None or not spec.docker.enabled):
148
+ issues.append(
149
+ ValidationIssue(
150
+ "warning",
151
+ "docker",
152
+ "Containers are defined but docker.enabled is not set — Docker will be installed",
153
+ )
154
+ )
155
+
156
+ # Nginx validations
157
+ if spec.nginx and spec.nginx.enabled:
158
+ if not spec.nginx.sites:
159
+ issues.append(
160
+ ValidationIssue(
161
+ "warning",
162
+ "nginx.sites",
163
+ "nginx.enabled=true but no sites defined",
164
+ )
165
+ )
166
+ for i, site in enumerate(spec.nginx.sites):
167
+ if not site.domain:
168
+ issues.append(
169
+ ValidationIssue(
170
+ "error",
171
+ f"nginx.sites[{i}].domain",
172
+ "Each nginx site requires a domain",
173
+ )
174
+ )
175
+ if site.ssl and (not site.ssl_certificate or not site.ssl_certificate_key):
176
+ issues.append(
177
+ ValidationIssue(
178
+ "error",
179
+ f"nginx.sites[{i}].ssl",
180
+ f"Site '{site.domain}' has ssl=true but missing "
181
+ "ssl_certificate or ssl_certificate_key",
182
+ )
183
+ )
184
+ if not (1 <= site.listen_port <= 65535):
185
+ issues.append(
186
+ ValidationIssue(
187
+ "error",
188
+ f"nginx.sites[{i}].listen_port",
189
+ f"Port {site.listen_port} is out of valid range 1-65535",
190
+ )
191
+ )
192
+
193
+ return issues
194
+
195
+
196
+ def validate_file_template(spec: FileTemplateSpec) -> list[ValidationIssue]:
197
+ issues: list[ValidationIssue] = []
198
+
199
+ # Must have at least one template
200
+ if not spec.templates:
201
+ issues.append(
202
+ ValidationIssue(
203
+ "error",
204
+ "templates",
205
+ "At least one template is required",
206
+ )
207
+ )
208
+
209
+ dests: set[str] = set()
210
+ for i, t in enumerate(spec.templates):
211
+ # src must not be empty
212
+ if not t.src:
213
+ issues.append(
214
+ ValidationIssue(
215
+ "error",
216
+ f"templates[{i}].src",
217
+ "Template source path must not be empty",
218
+ )
219
+ )
220
+
221
+ # dest must be an absolute path
222
+ if not t.dest or not t.dest.startswith("/"):
223
+ issues.append(
224
+ ValidationIssue(
225
+ "error",
226
+ f"templates[{i}].dest",
227
+ f"Template destination must be an absolute path, got '{t.dest}'",
228
+ )
229
+ )
230
+
231
+ # mode must be a valid octal string
232
+ if not re.match(r"^0?[0-7]{3,4}$", t.mode):
233
+ issues.append(
234
+ ValidationIssue(
235
+ "error",
236
+ f"templates[{i}].mode",
237
+ f"Invalid file mode '{t.mode}' — expected octal like '0644'",
238
+ )
239
+ )
240
+
241
+ # No duplicate destinations
242
+ if t.dest in dests:
243
+ issues.append(
244
+ ValidationIssue(
245
+ "error",
246
+ f"templates[{i}].dest",
247
+ f"Duplicate destination path: {t.dest}",
248
+ )
249
+ )
250
+ dests.add(t.dest)
251
+
252
+ return issues
253
+
254
+
255
+ def validate_compose_project(spec: ComposeProjectSpec) -> list[ValidationIssue]:
256
+ issues: list[ValidationIssue] = []
257
+
258
+ p = spec.project
259
+
260
+ # Project name must not be empty
261
+ if not p.name:
262
+ issues.append(
263
+ ValidationIssue(
264
+ "error",
265
+ "project.name",
266
+ "Compose project name must not be empty",
267
+ )
268
+ )
269
+
270
+ # Project directory must be absolute
271
+ if not p.directory or not p.directory.startswith("/"):
272
+ issues.append(
273
+ ValidationIssue(
274
+ "error",
275
+ "project.directory",
276
+ f"Project directory must be an absolute path, got '{p.directory}'",
277
+ )
278
+ )
279
+
280
+ # Template sources must not be empty
281
+ template_dests: set[str] = set()
282
+ for i, t in enumerate(p.templates):
283
+ if not t.src:
284
+ issues.append(
285
+ ValidationIssue(
286
+ "error",
287
+ f"project.templates[{i}].src",
288
+ "Template source path must not be empty",
289
+ )
290
+ )
291
+ if not t.dest:
292
+ issues.append(
293
+ ValidationIssue(
294
+ "error",
295
+ f"project.templates[{i}].dest",
296
+ "Template destination filename must not be empty",
297
+ )
298
+ )
299
+ if t.dest in template_dests:
300
+ issues.append(
301
+ ValidationIssue(
302
+ "error",
303
+ f"project.templates[{i}].dest",
304
+ f"Duplicate template destination: {t.dest}",
305
+ )
306
+ )
307
+ template_dests.add(t.dest)
308
+
309
+ # Health check values
310
+ hc = p.healthcheck
311
+ if hc.timeout <= 0:
312
+ issues.append(
313
+ ValidationIssue(
314
+ "error",
315
+ "project.healthcheck.timeout",
316
+ f"Health check timeout must be positive, got {hc.timeout}",
317
+ )
318
+ )
319
+ if hc.interval <= 0:
320
+ issues.append(
321
+ ValidationIssue(
322
+ "error",
323
+ "project.healthcheck.interval",
324
+ f"Health check interval must be positive, got {hc.interval}",
325
+ )
326
+ )
327
+
328
+ # Managed directory paths should be relative (not absolute)
329
+ for i, d in enumerate(p.directories):
330
+ if d.path.startswith("/"):
331
+ issues.append(
332
+ ValidationIssue(
333
+ "warning",
334
+ f"project.directories[{i}].path",
335
+ f"Directory path '{d.path}' is absolute — it will be used as-is, "
336
+ "not relative to project.directory",
337
+ )
338
+ )
339
+ if not re.match(r"^0?[0-7]{3,4}$", d.mode):
340
+ issues.append(
341
+ ValidationIssue(
342
+ "error",
343
+ f"project.directories[{i}].mode",
344
+ f"Invalid directory mode '{d.mode}' — expected octal like '0755'",
345
+ )
346
+ )
347
+
348
+ return issues
349
+
350
+
351
+ def validate_postgres_ensure(spec: PostgresEnsureSpec) -> list[ValidationIssue]:
352
+ issues: list[ValidationIssue] = []
353
+
354
+ # Must have at least one declaration
355
+ if not spec.users and not spec.databases and not spec.extensions and not spec.grants:
356
+ issues.append(
357
+ ValidationIssue(
358
+ "error",
359
+ "postgres_ensure",
360
+ "At least one user, database, extension, or grant must be declared",
361
+ )
362
+ )
363
+
364
+ # User names must be non-empty and unique
365
+ user_names: set[str] = set()
366
+ for i, u in enumerate(spec.users):
367
+ if not u.name:
368
+ issues.append(
369
+ ValidationIssue("error", f"users[{i}].name", "User name must not be empty")
370
+ )
371
+ if u.name in user_names:
372
+ issues.append(
373
+ ValidationIssue("error", f"users[{i}].name", f"Duplicate user name: {u.name}")
374
+ )
375
+ user_names.add(u.name)
376
+
377
+ # Database names must be non-empty and unique
378
+ db_names: set[str] = set()
379
+ for i, d in enumerate(spec.databases):
380
+ if not d.name:
381
+ issues.append(
382
+ ValidationIssue("error", f"databases[{i}].name", "Database name must not be empty")
383
+ )
384
+ if d.name in db_names:
385
+ issues.append(
386
+ ValidationIssue(
387
+ "error", f"databases[{i}].name", f"Duplicate database name: {d.name}"
388
+ )
389
+ )
390
+ db_names.add(d.name)
391
+
392
+ # Extension names must be non-empty
393
+ for i, e in enumerate(spec.extensions):
394
+ if not e.name:
395
+ issues.append(
396
+ ValidationIssue(
397
+ "error", f"extensions[{i}].name", "Extension name must not be empty"
398
+ )
399
+ )
400
+ if not e.database:
401
+ issues.append(
402
+ ValidationIssue(
403
+ "error",
404
+ f"extensions[{i}].database",
405
+ "Extension database must not be empty",
406
+ )
407
+ )
408
+
409
+ # Grant fields must be non-empty
410
+ for i, g in enumerate(spec.grants):
411
+ if not g.privilege:
412
+ issues.append(
413
+ ValidationIssue("error", f"grants[{i}].privilege", "Privilege must not be empty")
414
+ )
415
+ if not g.on_database:
416
+ issues.append(
417
+ ValidationIssue(
418
+ "error", f"grants[{i}].on_database", "on_database must not be empty"
419
+ )
420
+ )
421
+ if not g.to_user:
422
+ issues.append(
423
+ ValidationIssue("error", f"grants[{i}].to_user", "to_user must not be empty")
424
+ )
425
+
426
+ return issues
427
+
428
+
429
+ def validate_backup_job(spec: BackupJobSpec) -> list[ValidationIssue]:
430
+ issues: list[ValidationIssue] = []
431
+
432
+ b = spec.backup
433
+
434
+ if not b.name:
435
+ issues.append(ValidationIssue("error", "backup.name", "Backup job name must not be empty"))
436
+
437
+ if not b.destination.path or not b.destination.path.startswith("/"):
438
+ issues.append(
439
+ ValidationIssue(
440
+ "error",
441
+ "backup.destination.path",
442
+ f"Destination path must be an absolute path, got '{b.destination.path}'",
443
+ )
444
+ )
445
+
446
+ if b.retention.count < 1:
447
+ issues.append(
448
+ ValidationIssue(
449
+ "error",
450
+ "backup.retention.count",
451
+ f"Retention count must be at least 1, got {b.retention.count}",
452
+ )
453
+ )
454
+
455
+ if not b.schedule:
456
+ issues.append(ValidationIssue("error", "backup.schedule", "Schedule must not be empty"))
457
+
458
+ src = b.source
459
+ if src.type == "postgres_dump":
460
+ if not src.database:
461
+ issues.append(
462
+ ValidationIssue(
463
+ "error",
464
+ "backup.source.database",
465
+ "Database name is required for postgres_dump backups",
466
+ )
467
+ )
468
+ elif src.type == "directory":
469
+ if not src.path:
470
+ issues.append(
471
+ ValidationIssue(
472
+ "error",
473
+ "backup.source.path",
474
+ "Source path is required for directory backups",
475
+ )
476
+ )
477
+ elif not src.path.startswith("/"):
478
+ issues.append(
479
+ ValidationIssue(
480
+ "error",
481
+ "backup.source.path",
482
+ f"Source path must be absolute, got '{src.path}'",
483
+ )
484
+ )
485
+
486
+ return issues
487
+
488
+
489
+ def validate_systemd_unit(spec: SystemdUnitSpec) -> list[ValidationIssue]:
490
+ issues: list[ValidationIssue] = []
491
+
492
+ u = spec.unit
493
+
494
+ if not u.unit_name:
495
+ issues.append(ValidationIssue("error", "unit.unit_name", "Unit name must not be empty"))
496
+
497
+ if not u.exec_start:
498
+ issues.append(ValidationIssue("error", "unit.exec_start", "ExecStart must not be empty"))
499
+
500
+ valid_restart = ("no", "always", "on-failure", "on-abnormal", "on-abort", "on-success")
501
+ if u.restart not in valid_restart:
502
+ issues.append(
503
+ ValidationIssue(
504
+ "error",
505
+ "unit.restart",
506
+ f"Invalid restart policy '{u.restart}'. "
507
+ f"Must be one of: {', '.join(valid_restart)}",
508
+ )
509
+ )
510
+
511
+ valid_types = ("simple", "forking", "oneshot", "notify", "dbus", "idle")
512
+ if u.type not in valid_types:
513
+ issues.append(
514
+ ValidationIssue(
515
+ "error",
516
+ "unit.type",
517
+ f"Invalid service type '{u.type}'. " f"Must be one of: {', '.join(valid_types)}",
518
+ )
519
+ )
520
+
521
+ if u.restart_sec < 0:
522
+ issues.append(
523
+ ValidationIssue(
524
+ "error",
525
+ "unit.restart_sec",
526
+ f"RestartSec must be non-negative, got {u.restart_sec}",
527
+ )
528
+ )
529
+
530
+ # Logrotate validation
531
+ lr = spec.logrotate
532
+ if lr and lr.enabled:
533
+ if not lr.path:
534
+ issues.append(
535
+ ValidationIssue(
536
+ "error",
537
+ "logrotate.path",
538
+ "Logrotate path must not be empty when enabled",
539
+ )
540
+ )
541
+ valid_freq = ("daily", "weekly", "monthly")
542
+ if lr.frequency not in valid_freq:
543
+ issues.append(
544
+ ValidationIssue(
545
+ "error",
546
+ "logrotate.frequency",
547
+ f"Invalid frequency '{lr.frequency}'. "
548
+ f"Must be one of: {', '.join(valid_freq)}",
549
+ )
550
+ )
551
+ if lr.rotate < 1:
552
+ issues.append(
553
+ ValidationIssue(
554
+ "error",
555
+ "logrotate.rotate",
556
+ f"Rotate count must be at least 1, got {lr.rotate}",
557
+ )
558
+ )
559
+
560
+ return issues
561
+
562
+
563
+ def validate_systemd_timer(spec: SystemdTimerSpec) -> list[ValidationIssue]:
564
+ issues: list[ValidationIssue] = []
565
+
566
+ t = spec.timer
567
+ s = spec.service
568
+
569
+ if not t.timer_name:
570
+ issues.append(ValidationIssue("error", "timer.timer_name", "Timer name must not be empty"))
571
+
572
+ if not t.on_calendar:
573
+ issues.append(ValidationIssue("error", "timer.on_calendar", "OnCalendar must not be empty"))
574
+
575
+ if not s.exec_start:
576
+ issues.append(ValidationIssue("error", "service.exec_start", "ExecStart must not be empty"))
577
+
578
+ return issues
579
+
580
+
581
+ def validate_http_check(spec: HttpCheckSpec) -> list[ValidationIssue]:
582
+ issues: list[ValidationIssue] = []
583
+
584
+ c = spec.check
585
+
586
+ if not c.url:
587
+ issues.append(ValidationIssue("error", "check.url", "URL must not be empty"))
588
+ elif not c.url.startswith(("http://", "https://")):
589
+ issues.append(
590
+ ValidationIssue(
591
+ "error",
592
+ "check.url",
593
+ f"URL must start with http:// or https://, got '{c.url}'",
594
+ )
595
+ )
596
+
597
+ if not (100 <= c.expected_status <= 599):
598
+ issues.append(
599
+ ValidationIssue(
600
+ "error",
601
+ "check.expected_status",
602
+ f"Expected status must be 100-599, got {c.expected_status}",
603
+ )
604
+ )
605
+
606
+ if c.retries < 1:
607
+ issues.append(
608
+ ValidationIssue(
609
+ "error",
610
+ "check.retries",
611
+ f"Retries must be at least 1, got {c.retries}",
612
+ )
613
+ )
614
+
615
+ if c.interval < 0:
616
+ issues.append(
617
+ ValidationIssue(
618
+ "error",
619
+ "check.interval",
620
+ f"Interval must be non-negative, got {c.interval}",
621
+ )
622
+ )
623
+
624
+ if c.timeout <= 0:
625
+ issues.append(
626
+ ValidationIssue(
627
+ "error",
628
+ "check.timeout",
629
+ f"Timeout must be positive, got {c.timeout}",
630
+ )
631
+ )
632
+
633
+ return issues
634
+
635
+
636
+ def validate_stack(spec: StackSpec) -> list[ValidationIssue]:
637
+ issues: list[ValidationIssue] = []
638
+
639
+ # Must have at least one resource
640
+ if not spec.resources:
641
+ issues.append(
642
+ ValidationIssue(
643
+ "error",
644
+ "resources",
645
+ "Stack must contain at least one resource",
646
+ )
647
+ )
648
+
649
+ # Resource names must be unique
650
+ names: set[str] = set()
651
+ for i, res in enumerate(spec.resources):
652
+ if not res.name:
653
+ issues.append(
654
+ ValidationIssue(
655
+ "error",
656
+ f"resources[{i}].name",
657
+ "Resource name must not be empty",
658
+ )
659
+ )
660
+ if res.name in names:
661
+ issues.append(
662
+ ValidationIssue(
663
+ "error",
664
+ f"resources[{i}].name",
665
+ f"Duplicate resource name: {res.name}",
666
+ )
667
+ )
668
+ names.add(res.name)
669
+
670
+ # Check that referenced kinds are registered
671
+ from loft_cli_core.registry import get_spec_model, list_spec_kinds
672
+
673
+ if get_spec_model(res.kind) is None:
674
+ known = ", ".join(list_spec_kinds()) or "none"
675
+ issues.append(
676
+ ValidationIssue(
677
+ "error",
678
+ f"resources[{i}].kind",
679
+ f"Unknown resource kind '{res.kind}'. Supported: {known}",
680
+ )
681
+ )
682
+
683
+ # Check depends_on references exist
684
+ for dep in res.depends_on:
685
+ if dep not in names and dep != res.name:
686
+ # dep might refer to a resource defined later — defer full check
687
+ pass
688
+
689
+ # Full circular dependency check (topological sort)
690
+ name_set = {r.name for r in spec.resources}
691
+ for i, res in enumerate(spec.resources):
692
+ for dep in res.depends_on:
693
+ if dep not in name_set:
694
+ issues.append(
695
+ ValidationIssue(
696
+ "error",
697
+ f"resources[{i}].depends_on",
698
+ f"Dependency '{dep}' not found in stack resources",
699
+ )
700
+ )
701
+
702
+ # Detect cycles using DFS
703
+ adj: dict[str, list[str]] = {r.name: list(r.depends_on) for r in spec.resources}
704
+ visited: set[str] = set()
705
+ in_stack: set[str] = set()
706
+
707
+ def _has_cycle(node: str) -> bool:
708
+ if node in in_stack:
709
+ return True
710
+ if node in visited:
711
+ return False
712
+ visited.add(node)
713
+ in_stack.add(node)
714
+ for dep in adj.get(node, []):
715
+ if _has_cycle(dep):
716
+ return True
717
+ in_stack.discard(node)
718
+ return False
719
+
720
+ for name in adj:
721
+ if _has_cycle(name):
722
+ issues.append(
723
+ ValidationIssue(
724
+ "error",
725
+ "resources",
726
+ "Circular dependency detected in stack resources",
727
+ )
728
+ )
729
+ break
730
+
731
+ return issues
732
+
733
+
734
+ def validate_spec(spec) -> list[ValidationIssue]:
735
+ # Ensure built-in and addon kinds are registered (idempotent).
736
+ from loft_cli_core.registry import get_validator, load_addons
737
+
738
+ load_addons()
739
+
740
+ if isinstance(spec, list):
741
+ issues = []
742
+ for s in spec:
743
+ issues.extend(validate_spec(s))
744
+ return issues
745
+
746
+ validator = get_validator(spec.kind)
747
+ if validator is None:
748
+ return [
749
+ ValidationIssue("error", "kind", f"No validator registered for spec kind '{spec.kind}'")
750
+ ]
751
+ return validator(spec)
752
+
753
+
754
+ def has_errors(issues: list[ValidationIssue]) -> bool:
755
+ return any(i.severity == "error" for i in issues)