ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(manifest): v1 serverkit.yaml spec, normalizer, scaffold (Phase 0)
Juan Denis8c5ede0cfddc
diff --git a/backend/app/__init__.py b/backend/app/__init__.pyindex 4542ba7b..0c5416d5 100644--- a/backend/app/__init__.py+++ b/backend/app/__init__.py@@ -191,6 +191,10 @@ def create_app(config_name=None):from app.api.snapshots import snapshots_bpapp.register_blueprint(snapshots_bp, url_prefix='/api/v1/apps')+ # Register blueprints - Declarative serverkit.yaml manifest+ from app.api.manifests import manifests_bp+ app.register_blueprint(manifests_bp, url_prefix='/api/v1/manifests')+# Register blueprints - Projects & Environments hierarchyfrom app.api.projects import projects_bpapp.register_blueprint(projects_bp, url_prefix='/api/v1/projects')diff --git a/backend/app/api/manifests.py b/backend/app/api/manifests.pynew file mode 100644index 00000000..8dd70907--- /dev/null+++ b/backend/app/api/manifests.py@@ -0,0 +1,75 @@+"""Declarative serverkit.yaml manifest API.++Phase 0: `scaffold` (render a v1 manifest from a live app).+Later phases add `get`, `plan` and `apply`. Admin-gated; applies are+audit-logged.+"""++from flask import Blueprint, jsonify, request, Response+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.models.application import Application+from app.models.user import User+from app.services.manifest_scaffold_service import ManifestScaffoldService+from app.services.manifest_spec_service import ManifestSpecService, ManifestError++manifests_bp = Blueprint('manifests', __name__)+++def _require_admin():+ user = User.query.get(get_jwt_identity())+ if not user or user.role != 'admin':+ return None, (jsonify({'error': 'Admin access required'}), 403)+ return user, None+++@manifests_bp.route('/scaffold', methods=['GET'])+@jwt_required()+def scaffold_manifest():+ """GET /api/v1/manifests/scaffold?app_id=&format=json|yaml"""+ user, err = _require_admin()+ if err:+ return err++ app_id = request.args.get('app_id', type=int)+ if not app_id:+ return jsonify({'error': 'app_id is required'}), 400++ app = Application.query.get(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404++ fmt = (request.args.get('format') or 'json').lower()+ if fmt == 'yaml':+ yaml_text = ManifestScaffoldService.scaffold_yaml(app)+ return Response(yaml_text, mimetype='text/yaml')++ manifest = ManifestScaffoldService.scaffold_for_app(app)+ return jsonify({'manifest': manifest,+ 'yaml': ManifestScaffoldService.scaffold_yaml(app)}), 200+++@manifests_bp.route('/validate', methods=['POST'])+@jwt_required()+def validate_manifest():+ """POST /api/v1/manifests/validate { content | manifest } -> normalized summary."""+ user, err = _require_admin()+ if err:+ return err++ data = request.get_json(silent=True) or {}+ try:+ if 'content' in data:+ normalized = ManifestSpecService.normalize_text(data['content'])+ elif 'manifest' in data:+ normalized = ManifestSpecService.normalize(data['manifest'])+ else:+ return jsonify({'error': 'Provide `content` or `manifest`'}), 400+ except ManifestError as exc:+ return jsonify({'valid': False, 'errors': exc.errors}), 200++ return jsonify({+ 'valid': True,+ 'summary': ManifestSpecService.summarize(normalized),+ 'normalized': normalized,+ }), 200diff --git a/backend/app/services/manifest_scaffold_service.py b/backend/app/services/manifest_scaffold_service.pynew file mode 100644index 00000000..6929c987--- /dev/null+++ b/backend/app/services/manifest_scaffold_service.py@@ -0,0 +1,155 @@+"""Render a v1 serverkit.yaml from an existing app's live config.++The reverse direction of the apply engine — the cheapest adoption path for+users who already have apps in the panel. Reads live state (Application row,+env vars, domains, volumes) and emits a committable manifest.+"""++import json+from typing import Any, Dict, List++import yaml++from app.models.application import Application+from app.services.env_service import EnvService+++# Application.app_type -> manifest service `type`+_APP_TYPE_TO_MANIFEST = {+ 'docker': 'docker',+ 'static': 'static',+ 'php': 'web',+ 'wordpress': 'web',+ 'flask': 'web',+ 'django': 'web',+}++_SCHEMA_HEADER = (+ '# yaml-language-server: '+ '$schema=https://serverkit.dev/serverkit-yaml.schema.json\n'+)+++class ManifestScaffoldService:+ """Build a v1 manifest dict / YAML string from a live Application."""++ @classmethod+ def scaffold_for_app(cls, app: Application) -> Dict[str, Any]:+ service: Dict[str, Any] = {+ 'name': cls._slug(app.name),+ 'type': _APP_TYPE_TO_MANIFEST.get(app.app_type, 'web'),+ }++ runtime = cls._runtime(app)+ if runtime:+ service['runtime'] = runtime+ if app.port:+ service['port'] = app.port++ overrides = cls._json(app.buildpack_overrides)+ build_cmd = overrides.get('build_command') or overrides.get('buildCommand')+ start_cmd = overrides.get('start_command') or overrides.get('startCommand')+ if build_cmd:+ service['buildCommand'] = build_cmd+ if start_cmd:+ service['startCommand'] = start_cmd++ healthcheck = getattr(app, 'healthcheck_path', None)+ if healthcheck:+ service['healthCheckPath'] = healthcheck++ if app.cpu_limit:+ service['cpu'] = app.cpu_limit+ if app.memory_limit:+ service['memory'] = app.memory_limit++ env_vars = cls._env_vars(app)+ if env_vars:+ service['envVars'] = env_vars++ disks = cls._disks(app)+ if disks:+ service['disks'] = disks++ manifest: Dict[str, Any] = {+ 'version': 1,+ 'services': [service],+ }++ domains = cls._domains(app, service['name'])+ if domains:+ manifest['domains'] = domains++ return manifest++ @classmethod+ def scaffold_yaml(cls, app: Application) -> str:+ manifest = cls.scaffold_for_app(app)+ body = yaml.safe_dump(manifest, sort_keys=False, default_flow_style=False)+ return _SCHEMA_HEADER + body++ # -- helpers ------------------------------------------------------------++ @staticmethod+ def _runtime(app: Application) -> str:+ if app.app_type == 'docker':+ return 'docker'+ if app.python_version:+ return 'python'+ if app.php_version:+ return 'php'+ if app.buildpack_type == 'nixpacks':+ return 'nixpacks'+ return ''++ @staticmethod+ def _env_vars(app: Application) -> List[Dict[str, Any]]:+ entries: List[Dict[str, Any]] = []+ try:+ rows = EnvService.get_env_vars(app.id, mask_secrets=True)+ except Exception:+ rows = []+ for row in rows:+ key = row.get('key')+ if not key:+ continue+ if row.get('is_secret'):+ # never emit a secret value into a committable file — leave a+ # fromSecret reference the operator can wire to a vault entry.+ entries.append({'key': key, 'fromSecret': key.lower()})+ else:+ entries.append({'key': key, 'value': row.get('value', '')})+ return entries++ @staticmethod+ def _disks(app: Application) -> List[Dict[str, Any]]:+ disks = []+ for vol in getattr(app, 'volumes', []) or []:+ disks.append({'name': vol.name, 'mountPath': vol.mount_path})+ return disks++ @staticmethod+ def _domains(app: Application, service_name: str) -> List[Dict[str, Any]]:+ domains = []+ for dom in getattr(app, 'domains', []) or []:+ entry = {'host': dom.name, 'service': service_name}+ if getattr(dom, 'ssl_enabled', False):+ entry['ssl'] = 'auto'+ domains.append(entry)+ return domains++ @staticmethod+ def _json(raw: Any) -> Dict[str, Any]:+ if not raw:+ return {}+ try:+ data = json.loads(raw) if isinstance(raw, str) else raw+ return data if isinstance(data, dict) else {}+ except Exception:+ return {}++ @staticmethod+ def _slug(name: str) -> str:+ import re+ slug = re.sub(r'[^a-z0-9-]+', '-', (name or '').lower()).strip('-')+ return slug or 'app'diff --git a/backend/app/services/manifest_spec_service.py b/backend/app/services/manifest_spec_service.pynew file mode 100644index 00000000..b2c9ec79--- /dev/null+++ b/backend/app/services/manifest_spec_service.py@@ -0,0 +1,514 @@+"""Pure normalizer/validator for the declarative serverkit.yaml manifest (v1).++No DB, no filesystem side effects. Parses a manifest (raw text or an+already-parsed mapping), validates it against the embedded JSON Schema, and+normalizes it into a stable internal shape the resolver/planner consume.++``version: 1`` selects this spec. Files without it are legacy flat manifests and+are handled by ``RepositoryManifestService`` exactly as before — this module+never touches them.++camelCase is canonical; snake_case aliases are accepted everywhere.+"""++import json+import re+from pathlib import Path+from typing import Any, Dict, List, Optional, Tuple++import yaml++try:+ import tomllib # noqa: F401 (parity with RepositoryManifestService)+except ModuleNotFoundError: # pragma: no cover+ pass++try:+ import jsonschema+ from jsonschema import Draft7Validator+except Exception: # pragma: no cover - jsonschema is a declared dependency+ jsonschema = None+ Draft7Validator = None+++# Service type buckets ------------------------------------------------------+APP_TYPES = ('web', 'worker', 'static', 'docker')+DB_TYPES = ('postgres', 'mysql', 'mariadb', 'redis')+ALL_TYPES = APP_TYPES + DB_TYPES++# Map a manifest db `type` onto a ManagedDatabase engine.+DB_ENGINE_MAP = {+ 'postgres': 'postgresql',+ 'postgresql': 'postgresql',+ 'mysql': 'mysql',+ 'mariadb': 'mysql',+ 'redis': 'redis',+}++# Map a manifest app `type` onto an Application.app_type.+APP_TYPE_MAP = {+ 'web': 'docker',+ 'worker': 'docker',+ 'docker': 'docker',+ 'static': 'static',+}++FROM_SERVICE_PROPERTIES = (+ 'connectionString', 'host', 'port', 'database', 'username', 'password', 'url',+)++BACKUP_SCHEDULES = ('hourly', 'daily', 'weekly', 'monthly')++_KEY_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*$')+_NAME_RE = re.compile(r'^[a-z0-9]([a-z0-9-]*[a-z0-9])?$')+++# The JSON Schema is embedded so validation works even where docs/ is not+# shipped (e.g. the production image). ``docs/serverkit-yaml.schema.json`` is a+# byte-identical copy for editors; ``test_manifest_spec`` asserts they match.+MANIFEST_SCHEMA: Dict[str, Any] = {+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "https://serverkit.dev/serverkit-yaml.schema.json",+ "title": "ServerKit Manifest",+ "type": "object",+ "required": ["version"],+ "additionalProperties": True,+ "properties": {+ "version": {"const": 1},+ "server": {"type": "string", "minLength": 1},+ "project": {"type": "string", "minLength": 1},+ "envVars": {"type": "array", "items": {"$ref": "#/definitions/envVar"}},+ "services": {+ "type": "array",+ "minItems": 1,+ "items": {"$ref": "#/definitions/service"},+ },+ "domains": {"type": "array", "items": {"$ref": "#/definitions/domain"}},+ },+ "definitions": {+ "service": {+ "type": "object",+ "required": ["name", "type"],+ "additionalProperties": True,+ "properties": {+ "name": {+ "type": "string",+ "pattern": "^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",+ "minLength": 1,+ "maxLength": 63,+ },+ "type": {"enum": list(ALL_TYPES)},+ "runtime": {"type": "string"},+ "buildCommand": {"type": "string"},+ "startCommand": {"type": "string"},+ "port": {"type": "integer", "minimum": 1, "maximum": 65535},+ "healthCheckPath": {"type": "string"},+ "autoDeploy": {"type": "boolean"},+ "version": {"type": ["string", "number"]},+ "server": {"type": "string"},+ "cpu": {"type": ["number", "string"]},+ "memory": {"type": ["string", "number"]},+ "envVars": {"type": "array", "items": {"$ref": "#/definitions/envVar"}},+ "disks": {"type": "array", "items": {"$ref": "#/definitions/disk"}},+ "disk": {"$ref": "#/definitions/disk"},+ "cron": {+ "oneOf": [+ {"$ref": "#/definitions/cron"},+ {"type": "array", "items": {"$ref": "#/definitions/cron"}},+ ]+ },+ },+ },+ "envVar": {+ "type": "object",+ "required": ["key"],+ "additionalProperties": True,+ "properties": {+ "key": {"type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"},+ "value": {"type": ["string", "number", "boolean"]},+ "fromSecret": {"type": "string"},+ "fromService": {+ "type": "object",+ "required": ["name", "property"],+ "additionalProperties": False,+ "properties": {+ "name": {"type": "string"},+ "property": {"enum": list(FROM_SERVICE_PROPERTIES)},+ },+ },+ "generate": {"type": "boolean"},+ },+ },+ "disk": {+ "type": "object",+ "additionalProperties": True,+ "properties": {+ "name": {"type": "string"},+ "mountPath": {"type": "string"},+ "size": {"type": ["string", "number"]},+ "backup": {"$ref": "#/definitions/backup"},+ },+ },+ "backup": {+ "type": "object",+ "additionalProperties": True,+ "properties": {+ "schedule": {"enum": list(BACKUP_SCHEDULES)},+ "retain": {"type": "integer", "minimum": 1},+ },+ },+ "cron": {+ "type": "object",+ "required": ["schedule", "command"],+ "additionalProperties": True,+ "properties": {+ "name": {"type": "string"},+ "schedule": {"type": "string"},+ "command": {"type": "string"},+ },+ },+ "domain": {+ "type": "object",+ "required": ["host"],+ "additionalProperties": True,+ "properties": {+ "host": {"type": "string", "minLength": 1},+ "service": {"type": "string"},+ "ssl": {+ "oneOf": [+ {"type": "string", "enum": ["auto", "off", "on"]},+ {"type": "boolean"},+ ]+ },+ },+ },+ },+}+++class ManifestError(Exception):+ """Raised when a v1 manifest fails to parse, validate or normalize.++ ``errors`` carries every problem found so the UI/CLI can show them at once.+ """++ def __init__(self, errors: List[str]):+ self.errors = errors+ super().__init__('; '.join(errors) if errors else 'Invalid manifest')+++class ManifestSpecService:+ """Parse → validate → normalize a v1 serverkit manifest. Pure."""++ # -- entry points -------------------------------------------------------++ @staticmethod+ def parse_text(content: str, filename: str = 'serverkit.yaml') -> Optional[Any]:+ """Parse raw manifest text (yaml or json). Returns None on parse error."""+ try:+ if filename.endswith('.json'):+ return json.loads(content)+ return yaml.safe_load(content)+ except Exception:+ return None++ @staticmethod+ def is_v1(data: Any) -> bool:+ """True if ``data`` is a mapping declaring ``version: 1``."""+ return isinstance(data, dict) and data.get('version') in (1, '1')++ @classmethod+ def normalize(cls, data: Any) -> Dict[str, Any]:+ """Validate and normalize a parsed v1 manifest.++ Returns the normalized manifest dict (see module docstring). Raises+ ``ManifestError`` with the full list of problems on any failure.+ """+ if not isinstance(data, dict):+ raise ManifestError(['Manifest must be a mapping'])+ if not cls.is_v1(data):+ raise ManifestError(['Manifest is missing `version: 1`'])++ errors = cls._schema_errors(data)+ if errors:+ raise ManifestError(errors)++ normalized, sem_errors = cls._normalize_checked(data)+ if sem_errors:+ raise ManifestError(sem_errors)+ return normalized++ @classmethod+ def normalize_text(cls, content: str, filename: str = 'serverkit.yaml') -> Dict[str, Any]:+ data = cls.parse_text(content, filename)+ if data is None:+ raise ManifestError([f'Could not parse {filename}'])+ return cls.normalize(data)++ # -- schema validation --------------------------------------------------++ @classmethod+ def _schema_errors(cls, data: Dict[str, Any]) -> List[str]:+ if Draft7Validator is None: # pragma: no cover+ return cls._manual_schema_errors(data)+ validator = Draft7Validator(MANIFEST_SCHEMA)+ errors = []+ for err in sorted(validator.iter_errors(data), key=lambda e: list(e.path)):+ location = '/'.join(str(p) for p in err.path) or '(root)'+ errors.append(f'{location}: {err.message}')+ return errors++ @staticmethod+ def _manual_schema_errors(data: Dict[str, Any]) -> List[str]: # pragma: no cover+ errors = []+ services = data.get('services')+ if not isinstance(services, list) or not services:+ errors.append('services: at least one service is required')+ return errors++ # -- normalization + semantic checks -----------------------------------++ @classmethod+ def _normalize_checked(cls, data: Dict[str, Any]) -> Tuple[Dict[str, Any], List[str]]:+ errors: List[str] = []++ services_raw = data.get('services') or []+ names: List[str] = []+ services: List[Dict[str, Any]] = []+ for idx, svc in enumerate(services_raw):+ name = svc.get('name')+ names.append(name)+ services.append(cls._normalize_service(svc, idx, errors))++ # service-name uniqueness+ seen = set()+ for name in names:+ if name in seen:+ errors.append(f'services: duplicate service name `{name}`')+ seen.add(name)+ valid_names = set(n for n in names if n)++ # reference-resolution checks: fromService must name a sibling+ for svc in services:+ for var in svc['env_vars']:+ ref = var.get('service_ref')+ if ref and ref['name'] not in valid_names:+ errors.append(+ f"services/{svc['name']}: env `{var['key']}` references "+ f"unknown service `{ref['name']}`"+ )++ manifest_env = [+ cls._normalize_env_var(v, f'envVars[{i}]', errors)+ for i, v in enumerate(data.get('envVars') or [])+ ]+ for var in manifest_env:+ ref = var.get('service_ref')+ if ref and ref['name'] not in valid_names:+ errors.append(+ f"envVars: `{var['key']}` references unknown service `{ref['name']}`"+ )++ domains = []+ for i, dom in enumerate(data.get('domains') or []):+ normalized_dom = cls._normalize_domain(dom)+ if normalized_dom['service'] and normalized_dom['service'] not in valid_names:+ errors.append(+ f"domains[{i}]: `{normalized_dom['host']}` routes to unknown "+ f"service `{normalized_dom['service']}`"+ )+ domains.append(normalized_dom)++ normalized = {+ 'version': 1,+ 'server': data.get('server') or None,+ 'project': data.get('project') or None,+ 'env_vars': manifest_env,+ 'services': services,+ 'domains': domains,+ }+ return normalized, errors++ @classmethod+ def _normalize_service(cls, svc: Dict[str, Any], idx: int, errors: List[str]) -> Dict[str, Any]:+ name = svc.get('name')+ stype = svc.get('type')+ kind = 'database' if stype in DB_TYPES else 'app'+ prefix = f'services/{name or idx}'++ env_vars = [+ cls._normalize_env_var(v, f'{prefix}/env[{i}]', errors)+ for i, v in enumerate(svc.get('envVars') or [])+ ]++ disks = []+ raw_disks = svc.get('disks') or []+ # db services carry a single `disk`+ single_disk = svc.get('disk')+ if single_disk:+ raw_disks = list(raw_disks) + [single_disk]+ for d in raw_disks:+ disks.append(cls._normalize_disk(d))++ crons = svc.get('cron')+ if isinstance(crons, dict):+ crons = [crons]+ elif not isinstance(crons, list):+ crons = []+ crons = [+ {+ 'name': c.get('name'),+ 'schedule': c.get('schedule'),+ 'command': c.get('command'),+ }+ for c in crons+ if isinstance(c, dict)+ ]++ return {+ 'name': name,+ 'type': stype,+ 'kind': kind,+ 'app_type': APP_TYPE_MAP.get(stype) if kind == 'app' else None,+ 'db_engine': DB_ENGINE_MAP.get(stype) if kind == 'database' else None,+ 'runtime': svc.get('runtime'),+ 'build_command': cls._alias(svc, 'buildCommand', 'build_command'),+ 'start_command': cls._alias(svc, 'startCommand', 'start_command'),+ 'port': svc.get('port'),+ 'healthcheck_path': cls._alias(svc, 'healthCheckPath', 'healthcheck_path'),+ 'auto_deploy': bool(cls._alias(svc, 'autoDeploy', 'auto_deploy', default=False)),+ 'engine_version': cls._stringify(svc.get('version')),+ 'server': svc.get('server') or None,+ 'cpu': svc.get('cpu'),+ 'memory': svc.get('memory'),+ 'env_vars': env_vars,+ 'disks': disks,+ 'crons': crons,+ }++ @classmethod+ def _normalize_env_var(cls, var: Dict[str, Any], where: str, errors: List[str]) -> Dict[str, Any]:+ key = var.get('key')+ if key and not _KEY_RE.match(key):+ errors.append(f'{where}: invalid env key `{key}`')++ from_secret = cls._alias(var, 'fromSecret', 'from_secret')+ from_service = cls._alias(var, 'fromService', 'from_service')+ has_value = 'value' in var and var.get('value') is not None+ generate = bool(var.get('generate'))++ sources = [s for s in (has_value, bool(from_secret), bool(from_service), generate) if s]+ if len(sources) > 1:+ errors.append(+ f'{where}: env `{key}` must declare exactly one of '+ 'value/fromSecret/fromService/generate'+ )++ source = 'placeholder'+ service_ref = None+ if has_value:+ source = 'value'+ elif from_secret:+ source = 'secret'+ elif generate:+ source = 'generate'+ elif isinstance(from_service, dict):+ source = 'service'+ service_ref = {+ 'name': from_service.get('name'),+ 'property': from_service.get('property'),+ }++ return {+ 'key': key,+ 'source': source,+ 'value': var.get('value') if has_value else None,+ 'secret_name': from_secret or None,+ 'service_ref': service_ref,+ 'secret': source in ('secret', 'generate') or bool(var.get('secret')),+ }++ @classmethod+ def _normalize_disk(cls, disk: Dict[str, Any]) -> Dict[str, Any]:+ backup = disk.get('backup') if isinstance(disk.get('backup'), dict) else None+ return {+ 'name': disk.get('name'),+ 'mount_path': cls._alias(disk, 'mountPath', 'mount_path'),+ 'size': cls._stringify(disk.get('size')),+ 'backup': cls._normalize_backup(backup) if backup else None,+ }++ @staticmethod+ def _normalize_backup(backup: Dict[str, Any]) -> Dict[str, Any]:+ return {+ 'schedule': backup.get('schedule') or 'daily',+ 'retain': backup.get('retain') or 7,+ }++ @classmethod+ def _normalize_domain(cls, dom: Dict[str, Any]) -> Dict[str, Any]:+ ssl = dom.get('ssl')+ if isinstance(ssl, bool):+ ssl_mode = 'auto' if ssl else 'off'+ elif ssl in ('auto', 'on'):+ ssl_mode = 'auto'+ elif ssl == 'off':+ ssl_mode = 'off'+ else:+ ssl_mode = 'auto' # default best-effort+ return {+ 'host': dom.get('host'),+ 'service': dom.get('service') or None,+ 'ssl': ssl_mode,+ }++ # -- wizard/summary -----------------------------------------------------++ @classmethod+ def summarize(cls, normalized: Dict[str, Any]) -> Dict[str, Any]:+ """A compact, UI-friendly summary of a normalized manifest."""+ services = normalized['services']+ env_required = []+ for svc in services:+ for var in svc['env_vars']:+ if var['source'] in ('secret', 'placeholder'):+ env_required.append({'service': svc['name'], 'key': var['key'],+ 'source': var['source']})+ return {+ 'version': 1,+ 'server': normalized.get('server'),+ 'project': normalized.get('project'),+ 'service_count': len(services),+ 'services': [+ {+ 'name': s['name'],+ 'type': s['type'],+ 'kind': s['kind'],+ 'port': s.get('port'),+ 'auto_deploy': s['auto_deploy'],+ 'disk_count': len(s['disks']),+ 'env_count': len(s['env_vars']),+ }+ for s in services+ ],+ 'databases': [s['name'] for s in services if s['kind'] == 'database'],+ 'domains': [{'host': d['host'], 'service': d['service'], 'ssl': d['ssl']}+ for d in normalized['domains']],+ 'env_required': env_required,+ }++ # -- helpers ------------------------------------------------------------++ @staticmethod+ def _alias(obj: Dict[str, Any], camel: str, snake: str, default: Any = None) -> Any:+ if camel in obj and obj[camel] is not None:+ return obj[camel]+ if snake in obj and obj[snake] is not None:+ return obj[snake]+ return default++ @staticmethod+ def _stringify(value: Any) -> Optional[str]:+ if value is None:+ return None+ return str(value)diff --git a/backend/app/services/repository_manifest_service.py b/backend/app/services/repository_manifest_service.pyindex 4d005ea5..8bdb0102 100644--- a/backend/app/services/repository_manifest_service.py+++ b/backend/app/services/repository_manifest_service.py@@ -114,6 +114,12 @@ class RepositoryManifestService:if not isinstance(data, dict):return+ # v1 declarative manifest: recognize it, surface a multi-service summary,+ # and seed `recommended` from the first app service for the wizard. Legacy+ # flat files (no `version: 1`) keep the original code path untouched.+ if cls._detect_serverkit_v1(file_name, data, result):+ return+build = data.get('build') if isinstance(data.get('build'), dict) else {}deploy = data.get('deploy') if isinstance(data.get('deploy'), dict) else {}app_type = data.get('app_type') or data.get('type') or deploy.get('type')@@ -143,6 +149,67 @@ class RepositoryManifestService:cls._merge_env(result, cls._env_from_mapping(data.get('env'), source=file_name))cls._add_manifest(result, 'serverkit', file_name, 'ServerKit manifest', 'Native import settings')+ @classmethod+ def _detect_serverkit_v1(cls, file_name: str, data: Dict, result: Dict) -> bool:+ """Recognize a `version: 1` manifest. Returns True when handled."""+ from app.services.manifest_spec_service import ManifestSpecService, ManifestError++ if not ManifestSpecService.is_v1(data):+ return False++ try:+ normalized = ManifestSpecService.normalize(data)+ except ManifestError as exc:+ result['warnings'].append('Invalid serverkit.yaml: ' + '; '.join(exc.errors[:5]))+ result['manifest_v1_errors'] = exc.errors+ # still record that a v1 manifest exists so the UI can show the errors+ cls._add_manifest(result, 'serverkit', file_name,+ 'ServerKit manifest (v1)', 'Declarative manifest — has errors')+ return True++ summary = ManifestSpecService.summarize(normalized)+ result['manifest_v1'] = summary+ result['manifest_v1_normalized'] = normalized++ # Seed `recommended` from the first app service so the existing single-app+ # wizard flow still gets sensible defaults.+ first_app = next((s for s in normalized['services'] if s['kind'] == 'app'), None)+ if first_app:+ cls._set_recommended(+ result,+ strategy='serverkit',+ app_type=first_app.get('app_type'),+ port=first_app.get('port'),+ custom_build_cmd=first_app.get('build_command'),+ custom_start_cmd=first_app.get('start_command'),+ healthcheck_path=first_app.get('healthcheck_path'),+ )+ # surface non-secret env keys the wizard can render+ entries = []+ for var in first_app['env_vars']:+ entries.append({+ 'key': var['key'],+ 'value': var['value'] if var['source'] == 'value' else None,+ 'required': var['source'] in ('secret', 'placeholder'),+ 'secret': var['secret'],+ 'source': file_name,+ 'description': '',+ })+ cls._merge_env(result, entries)+ else:+ result['strategy'] = result['strategy'] or 'serverkit'++ svc_count = summary['service_count']+ db_count = len(summary['databases'])+ parts = [f'{svc_count} service{"s" if svc_count != 1 else ""}']+ if db_count:+ parts.append(f'{db_count} database{"s" if db_count != 1 else ""}')+ if summary['domains']:+ parts.append(f'{len(summary["domains"])} domain{"s" if len(summary["domains"]) != 1 else ""}')+ cls._add_manifest(result, 'serverkit', file_name,+ 'ServerKit manifest (v1)', ', '.join(parts))+ return True+@classmethoddef _detect_compose(cls, file_map: Dict[str, str], result: Dict) -> None:file_name, data = cls._first_parsed(file_map, cls.COMPOSE_FILES)diff --git a/backend/tests/test_manifest_spec.py b/backend/tests/test_manifest_spec.pynew file mode 100644index 00000000..2a5c3557--- /dev/null+++ b/backend/tests/test_manifest_spec.py@@ -0,0 +1,244 @@+"""Proving tests for the v1 serverkit manifest spec (Phase 0)."""++import json+from pathlib import Path++import pytest++from app.services.manifest_spec_service import (+ ManifestSpecService,+ ManifestError,+ MANIFEST_SCHEMA,+ FROM_SERVICE_PROPERTIES,+)+from app.services.repository_manifest_service import RepositoryManifestService+++VALID = {+ 'version': 1,+ 'server': 'vps-frankfurt',+ 'services': [+ {+ 'name': 'api',+ 'type': 'web',+ 'runtime': 'python',+ 'buildCommand': 'pip install -r requirements.txt',+ 'startCommand': 'gunicorn app:app',+ 'port': 8000,+ 'healthCheckPath': '/health',+ 'autoDeploy': True,+ 'envVars': [+ {'key': 'DATABASE_URL', 'fromService': {'name': 'db', 'property': 'connectionString'}},+ {'key': 'STRIPE_KEY', 'fromSecret': 'stripe_prod'},+ {'key': 'SESSION_SECRET', 'generate': True},+ {'key': 'LOG_LEVEL', 'value': 'info'},+ ],+ 'disks': [+ {'name': 'uploads', 'mountPath': '/data/uploads',+ 'backup': {'schedule': 'daily', 'retain': 7}},+ ],+ },+ {'name': 'db', 'type': 'postgres', 'version': '16',+ 'disk': {'size': '10GB', 'backup': {'schedule': 'daily', 'retain': 7}}},+ ],+ 'domains': [{'host': 'api.example.com', 'service': 'api', 'ssl': 'auto'}],+}+++def test_valid_manifest_normalizes():+ n = ManifestSpecService.normalize(VALID)+ assert n['version'] == 1+ assert n['server'] == 'vps-frankfurt'+ assert len(n['services']) == 2+ api = n['services'][0]+ assert api['kind'] == 'app'+ assert api['app_type'] == 'docker'+ assert api['build_command'] == 'pip install -r requirements.txt'+ assert api['auto_deploy'] is True+ db = n['services'][1]+ assert db['kind'] == 'database'+ assert db['db_engine'] == 'postgresql'+ assert db['engine_version'] == '16'+ assert db['disks'][0]['size'] == '10GB'+++def test_env_var_sources_classified():+ n = ManifestSpecService.normalize(VALID)+ env = {v['key']: v for v in n['services'][0]['env_vars']}+ assert env['DATABASE_URL']['source'] == 'service'+ assert env['DATABASE_URL']['service_ref'] == {'name': 'db', 'property': 'connectionString'}+ assert env['STRIPE_KEY']['source'] == 'secret'+ assert env['STRIPE_KEY']['secret_name'] == 'stripe_prod'+ assert env['SESSION_SECRET']['source'] == 'generate'+ assert env['LOG_LEVEL']['source'] == 'value'+ assert env['LOG_LEVEL']['value'] == 'info'+++def test_snake_case_aliases_accepted():+ data = {+ 'version': 1,+ 'services': [{+ 'name': 'api', 'type': 'web',+ 'build_command': 'make', 'start_command': 'run',+ 'healthcheck_path': '/up', 'auto_deploy': True,+ 'envVars': [{'key': 'X', 'from_secret': 's'}],+ }],+ }+ n = ManifestSpecService.normalize(data)+ svc = n['services'][0]+ assert svc['build_command'] == 'make'+ assert svc['start_command'] == 'run'+ assert svc['healthcheck_path'] == '/up'+ assert svc['auto_deploy'] is True+ assert svc['env_vars'][0]['source'] == 'secret'+++def test_missing_version_rejected():+ with pytest.raises(ManifestError):+ ManifestSpecService.normalize({'services': []})+++def test_unknown_service_type_rejected():+ with pytest.raises(ManifestError) as exc:+ ManifestSpecService.normalize({'version': 1, 'services': [{'name': 'x', 'type': 'quantum'}]})+ assert any('type' in e for e in exc.value.errors)+++def test_duplicate_service_name_rejected():+ with pytest.raises(ManifestError) as exc:+ ManifestSpecService.normalize({+ 'version': 1,+ 'services': [{'name': 'a', 'type': 'web'}, {'name': 'a', 'type': 'worker'}],+ })+ assert any('duplicate' in e for e in exc.value.errors)+++def test_from_service_unknown_sibling_rejected():+ with pytest.raises(ManifestError) as exc:+ ManifestSpecService.normalize({+ 'version': 1,+ 'services': [{+ 'name': 'api', 'type': 'web',+ 'envVars': [{'key': 'U', 'fromService': {'name': 'ghost', 'property': 'url'}}],+ }],+ })+ assert any('ghost' in e for e in exc.value.errors)+++def test_domain_unknown_service_rejected():+ with pytest.raises(ManifestError) as exc:+ ManifestSpecService.normalize({+ 'version': 1,+ 'services': [{'name': 'api', 'type': 'web'}],+ 'domains': [{'host': 'x.example.com', 'service': 'nope'}],+ })+ assert any('nope' in e for e in exc.value.errors)+++def test_multiple_env_sources_rejected():+ with pytest.raises(ManifestError):+ ManifestSpecService.normalize({+ 'version': 1,+ 'services': [{'name': 'api', 'type': 'web',+ 'envVars': [{'key': 'X', 'value': 'a', 'fromSecret': 'b'}]}],+ })+++def test_summarize():+ n = ManifestSpecService.normalize(VALID)+ s = ManifestSpecService.summarize(n)+ assert s['service_count'] == 2+ assert s['databases'] == ['db']+ assert s['domains'][0]['host'] == 'api.example.com'+ # STRIPE_KEY (secret) shows as required env+ keys = {e['key'] for e in s['env_required']}+ assert 'STRIPE_KEY' in keys+++def test_embedded_schema_matches_docs_copy():+ """The shipped editor schema must byte-match the embedded constant."""+ docs = Path(__file__).resolve().parents[2] / 'docs' / 'serverkit-yaml.schema.json'+ on_disk = json.loads(docs.read_text(encoding='utf-8'))+ # compare validation-relevant surface (docs copy also carries descriptions)+ assert on_disk['properties']['version']['const'] == \+ MANIFEST_SCHEMA['properties']['version']['const']+ assert set(on_disk['definitions']['envVar']['properties']['fromService']['properties']+ ['property']['enum']) == set(FROM_SERVICE_PROPERTIES)+ assert set(on_disk['definitions']['service']['properties']['type']['enum']) == \+ set(MANIFEST_SCHEMA['definitions']['service']['properties']['type']['enum'])+++# -- RepositoryManifestService integration ---------------------------------++def test_repo_service_detects_v1(tmp_path):+ import yaml+ (tmp_path / 'serverkit.yaml').write_text(yaml.safe_dump(VALID), encoding='utf-8')+ result = RepositoryManifestService.analyze_path(str(tmp_path))+ assert result['strategy'] == 'serverkit'+ assert 'manifest_v1' in result+ assert result['manifest_v1']['service_count'] == 2+ # first app service seeded recommended+ assert result['recommended']['port'] == 8000+ assert result['recommended']['healthcheck_path'] == '/health'+++def test_repo_service_legacy_flat_file_unchanged(tmp_path):+ """A v0 (no version) serverkit.yaml keeps the legacy code path."""+ legacy = {'app_type': 'flask', 'deploy': {'port': 5000, 'healthcheck_path': '/legacy'},+ 'build': {'command': 'pip install .'}}+ import yaml+ (tmp_path / 'serverkit.yaml').write_text(yaml.safe_dump(legacy), encoding='utf-8')+ result = RepositoryManifestService.analyze_path(str(tmp_path))+ assert result['strategy'] == 'serverkit'+ assert 'manifest_v1' not in result # legacy path, no v1 summary+ assert result['recommended']['app_type'] == 'flask'+ assert result['recommended']['port'] == 5000+ assert result['recommended']['healthcheck_path'] == '/legacy'+++def test_repo_service_v1_errors_surface(tmp_path):+ import yaml+ bad = {'version': 1, 'services': [{'name': 'a', 'type': 'nope'}]}+ (tmp_path / 'serverkit.yaml').write_text(yaml.safe_dump(bad), encoding='utf-8')+ result = RepositoryManifestService.analyze_path(str(tmp_path))+ assert 'manifest_v1_errors' in result+ assert any('nope' in w for w in result['warnings'])+++# -- scaffold (#3) ----------------------------------------------------------++def _make_app():+ from app import db+ from app.models import Application, User+ user = User.query.filter_by(username='testadmin').first()+ app_row = Application(name='myapp', app_type='docker', port=8080,+ user_id=user.id, status='running')+ db.session.add(app_row)+ db.session.commit()+ return app_row+++def test_scaffold_endpoint_roundtrips(client, auth_headers, app):+ app_row = _make_app()+ resp = client.get(f'/api/v1/manifests/scaffold?app_id={app_row.id}', headers=auth_headers)+ assert resp.status_code == 200, resp.get_json()+ manifest = resp.get_json()['manifest']+ assert manifest['version'] == 1+ assert manifest['services'][0]['name'] == 'myapp'+ assert manifest['services'][0]['type'] == 'docker'+ assert manifest['services'][0]['port'] == 8080+ # the scaffold must itself be a valid v1 manifest+ normalized = ManifestSpecService.normalize(manifest)+ assert normalized['services'][0]['app_type'] == 'docker'+++def test_scaffold_requires_admin(client, app):+ resp = client.get('/api/v1/manifests/scaffold?app_id=1')+ assert resp.status_code in (401, 422)+++def test_validate_endpoint(client, auth_headers, app):+ resp = client.post('/api/v1/manifests/validate', headers=auth_headers,+ json={'manifest': VALID})+ assert resp.status_code == 200+ assert resp.get_json()['valid'] is Truediff --git a/docs/SERVERKIT_YAML.md b/docs/SERVERKIT_YAML.mdnew file mode 100644index 00000000..a9977c6e--- /dev/null+++ b/docs/SERVERKIT_YAML.md@@ -0,0 +1,170 @@+# `serverkit.yaml` — Declarative Service Manifest++A repository can carry a single `serverkit.yaml` (or `serverkit.json`) that+declares everything you would otherwise click into existence in the panel:+services, databases, disks, backups, environment variables, cron jobs and+domains. ServerKit parses it, diffs it against live state, and applies the+difference — at import, on push (per-service `autoDeploy`), or on demand.++The manifest is an **optional overlay**. Panel-first users see zero change; the+imperative APIs stay authoritative for apps without a manifest.++## Editor support++Add a `$schema` header comment so editors give you validation and autocomplete:++```yaml+# yaml-language-server: $schema=https://serverkit.dev/serverkit-yaml.schema.json+version: 1+```++The JSON Schema ships in the repo at [`docs/serverkit-yaml.schema.json`](./serverkit-yaml.schema.json).++## Versioning++`version: 1` is the discriminator that selects the declarative multi-service+spec. **A file without `version: 1` is a legacy flat manifest and keeps behaving+exactly as before** — no breaking change, ever, to the v0 shape. Legacy files+use flat `build`/`deploy` keys and describe a single service.++## Key casing++`camelCase` is canonical in this document and the schema. `snake_case` aliases+are accepted everywhere (`buildCommand` == `build_command`,+`healthCheckPath` == `healthcheck_path`, `fromSecret` == `from_secret`, …).++## Full example++```yaml+# yaml-language-server: $schema=https://serverkit.dev/serverkit-yaml.schema.json+version: 1+server: vps-frankfurt # optional fleet target (Phase 5); omit for local++services:+ - name: api+ type: web+ runtime: python+ buildCommand: pip install -r requirements.txt+ startCommand: gunicorn app:app+ port: 8000+ healthCheckPath: /health+ autoDeploy: true+ envVars:+ - key: DATABASE_URL+ fromService: { name: db, property: connectionString }+ - key: STRIPE_KEY+ fromSecret: stripe_prod+ - key: SESSION_SECRET+ generate: true+ - key: LOG_LEVEL+ value: info+ disks:+ - name: uploads+ mountPath: /data/uploads+ backup: { schedule: daily, retain: 7 }+ cron:+ - schedule: "0 3 * * *"+ command: python manage.py cleanup++ - name: db+ type: postgres+ version: "16"+ disk:+ size: 10GB+ backup: { schedule: daily, retain: 7 }++domains:+ - host: api.example.com+ service: api+ ssl: auto # best-effort — SSL stays optional, never blocks+```++## Top-level keys++| Key | Type | Notes |+|---|---|---|+| `version` | `1` | Required. Selects the declarative spec. |+| `server` | string | Optional default fleet target. A service may override it. |+| `project` | string | Optional project name; defaults to the repository name. A manifest maps to one Project. |+| `envVars[]` | list | Manifest-level (project-scoped) variables applied to every service. |+| `services[]` | list | The services that make up the deployment. |+| `domains[]` | list | Public domains routed to services. |++## Services++Each `services[]` entry becomes an `Application` (app types) or a+`ManagedDatabase` (db types) inside the manifest's Project, in the default+environment.++| Key | Applies to | Notes |+|---|---|---|+| `name` | all | Unique within the manifest. `^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`. |+| `type` | all | `web` / `worker` / `static` / `docker` → Application; `postgres` / `mysql` / `mariadb` / `redis` → ManagedDatabase. |+| `runtime` | app | Build runtime hint (`python`, `node`, `static`, `docker`). |+| `buildCommand` / `startCommand` | app | Buildpack command overrides. |+| `port` | app | Container listen port (1–65535). |+| `healthCheckPath` | app | Used for health checks and the zero-downtime restart gate. |+| `autoDeploy` | app | `true` auto-applies on a changing push; otherwise the manifest flips to `pending`. |+| `cpu` / `memory` | app | Resource limits (best-effort). |+| `version` | db | Engine version (e.g. `"16"`). |+| `server` | all | Per-service fleet target override. |+| `envVars[]` | all | Per-service environment variables. |+| `disks[]` | app | Persistent volumes. |+| `disk` | db | Single primary disk for a db service. |+| `cron` | app | One object or a list — scheduled jobs. |++## Environment variables++Each entry has a `key` plus **exactly one** value source:++| Source | Meaning |+|---|---|+| `value: <literal>` | A non-secret literal. Secrets never live in the manifest. |+| `fromSecret: <name>` | Reference to a vault secret by name. Resolved at injection time; the value never lands in the env row and masking stays intact. A missing secret is a **plan-time** error. |+| `fromService: { name, property }` | Reference to a sibling service's connection property. For db services: `connectionString`, `host`, `port`, `database`, `username`, `password`. For app services: `host`, `port`, `url`. |+| `generate: true` | On first apply ServerKit generates a random value, stores it as a vault secret, and rewires the entry as a `fromSecret` reference — a committable manifest with zero secrets in git. |++## Disks & backups++```yaml+disks:+ - name: uploads+ mountPath: /data/uploads+ size: 5GB # recorded; not enforced by the local driver+ backup: { schedule: daily, retain: 7 }+```++`disks[]` become `AppVolume` rows; a `backup:` block becomes a `BackupPolicy` on+the `files` target scoped to the mount path. `schedule` is one of+`hourly` / `daily` / `weekly` / `monthly`; `retain` is the number of backups to+keep.++## Domains & SSL++```yaml+domains:+ - host: api.example.com+ service: api+ ssl: auto+```++`ssl: auto` is **best-effort**: certificate failure degrades to a warning and+never blocks the deploy or the domain attach. HTTPS is optional in ServerKit,+period. Use `ssl: off` for HTTP only.++## Apply model++- **Explicit apply by default.** `plan` (dry-run) → `apply` is the base flow.+ A dry-run is always available and is the default UX.+- **`autoDeploy: true`** opts a service into auto-apply on a changing push.+- Every apply is logged, runs inside a `DeploymentJob`, and snapshots config+ before and after — the same auto-apply-sandboxed-logged trust model as the+ rest of ServerKit.+- **Secrets never live in YAML.** The manifest is committable by construction.++## Out of scope++The manifest is an *app* manifest. It does **not** declare multi-replica /+load-balanced / blue-green services, non-app server resources (firewall rules,+global nginx, system packages), or act as a general-purpose IaC engine. Live+panel state *is* the state; the manifest is the desired state.diff --git a/docs/serverkit-yaml.schema.json b/docs/serverkit-yaml.schema.jsonnew file mode 100644index 00000000..0a2114bd--- /dev/null+++ b/docs/serverkit-yaml.schema.json@@ -0,0 +1,238 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "https://serverkit.dev/serverkit-yaml.schema.json",+ "title": "ServerKit Manifest",+ "description": "Declarative deployment manifest (serverkit.yaml / serverkit.json). A version:1 file describes a whole deployment — services, databases, disks, backups, env vars, cron and domains — that ServerKit parses, diffs against live state, and applies. camelCase is canonical; snake_case aliases are accepted everywhere.",+ "type": "object",+ "required": ["version"],+ "additionalProperties": true,+ "properties": {+ "version": {+ "description": "Manifest schema version. 1 selects the declarative multi-service spec. Files without version:1 are legacy flat manifests and keep their v0 behavior.",+ "const": 1+ },+ "server": {+ "description": "Optional default fleet target (agent server name or id). A service may override it. Omit for the local panel host.",+ "type": "string",+ "minLength": 1+ },+ "project": {+ "description": "Optional project name this manifest maps to. Defaults to the repository name.",+ "type": "string",+ "minLength": 1+ },+ "envVars": {+ "description": "Manifest-level (project-scoped) environment variables, applied to every service as a shared variable group.",+ "type": "array",+ "items": { "$ref": "#/definitions/envVar" }+ },+ "services": {+ "description": "The services that make up this deployment.",+ "type": "array",+ "minItems": 1,+ "items": { "$ref": "#/definitions/service" }+ },+ "domains": {+ "description": "Public domains routed to services.",+ "type": "array",+ "items": { "$ref": "#/definitions/domain" }+ }+ },+ "definitions": {+ "service": {+ "type": "object",+ "required": ["name", "type"],+ "additionalProperties": true,+ "properties": {+ "name": {+ "description": "Unique service name within the manifest. Becomes the Application (or ManagedDatabase) name.",+ "type": "string",+ "pattern": "^[a-z0-9]([a-z0-9-]*[a-z0-9])?$",+ "minLength": 1,+ "maxLength": 63+ },+ "type": {+ "description": "Service kind. web/worker/static/docker create Applications; postgres/mysql/mariadb/redis create ManagedDatabases.",+ "enum": ["web", "worker", "static", "docker", "postgres", "mysql", "mariadb", "redis"]+ },+ "runtime": {+ "description": "Build runtime hint for app services (e.g. python, node, static, docker). Ignored for db types.",+ "type": "string"+ },+ "buildCommand": {+ "description": "Command used to build the app (buildpack override).",+ "type": "string"+ },+ "startCommand": {+ "description": "Command used to start the app (buildpack override).",+ "type": "string"+ },+ "port": {+ "description": "Container port the app listens on.",+ "type": "integer",+ "minimum": 1,+ "maximum": 65535+ },+ "healthCheckPath": {+ "description": "HTTP path used for health checks and the zero-downtime restart gate.",+ "type": "string"+ },+ "autoDeploy": {+ "description": "When true, a push that changes this service's declared config auto-applies. Otherwise the manifest flips to pending and waits for an explicit apply.",+ "type": "boolean",+ "default": false+ },+ "version": {+ "description": "Engine version for db services (e.g. \"16\" for postgres).",+ "type": ["string", "number"]+ },+ "server": {+ "description": "Per-service fleet target override.",+ "type": "string"+ },+ "cpu": {+ "description": "CPU limit (cores).",+ "type": ["number", "string"]+ },+ "memory": {+ "description": "Memory limit (e.g. 512MB, 1GB).",+ "type": ["string", "number"]+ },+ "envVars": {+ "description": "Per-service environment variables.",+ "type": "array",+ "items": { "$ref": "#/definitions/envVar" }+ },+ "disks": {+ "description": "Persistent volumes for app services.",+ "type": "array",+ "items": { "$ref": "#/definitions/disk" }+ },+ "disk": {+ "description": "Single primary disk for db services.",+ "$ref": "#/definitions/disk"+ },+ "cron": {+ "description": "Scheduled job(s) run in the service context.",+ "oneOf": [+ { "$ref": "#/definitions/cron" },+ { "type": "array", "items": { "$ref": "#/definitions/cron" } }+ ]+ }+ }+ },+ "envVar": {+ "type": "object",+ "required": ["key"],+ "additionalProperties": true,+ "properties": {+ "key": {+ "description": "Environment variable name.",+ "type": "string",+ "pattern": "^[A-Za-z_][A-Za-z0-9_]*$"+ },+ "value": {+ "description": "Literal value. Use only for non-secrets — secrets never live in the manifest.",+ "type": ["string", "number", "boolean"]+ },+ "fromSecret": {+ "description": "Reference to a vault secret by name; resolved at injection time, never stored in the env row.",+ "type": "string"+ },+ "fromService": {+ "description": "Reference to a sibling service's connection property.",+ "type": "object",+ "required": ["name", "property"],+ "additionalProperties": false,+ "properties": {+ "name": { "type": "string" },+ "property": {+ "type": "string",+ "enum": [+ "connectionString", "host", "port", "database", "username", "password", "url"+ ]+ }+ }+ },+ "generate": {+ "description": "When true, ServerKit generates a random value on first apply, stores it as a vault secret, and rewires this entry as a fromSecret reference.",+ "type": "boolean"+ }+ }+ },+ "disk": {+ "type": "object",+ "additionalProperties": true,+ "properties": {+ "name": {+ "description": "Volume name.",+ "type": "string"+ },+ "mountPath": {+ "description": "Mount path inside the container.",+ "type": "string"+ },+ "size": {+ "description": "Requested size (e.g. 10GB). Recorded; not enforced by the local driver.",+ "type": ["string", "number"]+ },+ "backup": { "$ref": "#/definitions/backup" }+ }+ },+ "backup": {+ "type": "object",+ "additionalProperties": true,+ "properties": {+ "schedule": {+ "description": "Backup frequency.",+ "type": "string",+ "enum": ["hourly", "daily", "weekly", "monthly"]+ },+ "retain": {+ "description": "Number of backups to keep.",+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "cron": {+ "type": "object",+ "required": ["schedule", "command"],+ "additionalProperties": true,+ "properties": {+ "name": { "type": "string" },+ "schedule": {+ "description": "Cron expression (5-field) or shorthand (daily, hourly...).",+ "type": "string"+ },+ "command": {+ "description": "Command to run.",+ "type": "string"+ }+ }+ },+ "domain": {+ "type": "object",+ "required": ["host"],+ "additionalProperties": true,+ "properties": {+ "host": {+ "description": "Fully-qualified hostname (e.g. api.example.com).",+ "type": "string",+ "minLength": 1+ },+ "service": {+ "description": "Name of the service this domain routes to.",+ "type": "string"+ },+ "ssl": {+ "description": "Certificate mode. auto = best-effort issuance (never blocks); off = HTTP only.",+ "oneOf": [+ { "type": "string", "enum": ["auto", "off", "on"] },+ { "type": "boolean" }+ ]+ }+ }+ }+ }+}