diff --git a/Pmoves-Health-wger b/Pmoves-Health-wger index 341c7e065d..bfef5b1867 160000 --- a/Pmoves-Health-wger +++ b/Pmoves-Health-wger @@ -1 +1 @@ -Subproject commit 341c7e065d7de801ea42ffeb8d0421f310cef0a9 +Subproject commit bfef5b1867f2a2f0020a4e98c1276652898f2522 diff --git a/pmoves/bootstrap/registry.json b/pmoves/bootstrap/registry.json index d62ce27ee5..42892da583 100644 --- a/pmoves/bootstrap/registry.json +++ b/pmoves/bootstrap/registry.json @@ -886,6 +886,84 @@ } } ] + }, + { + "id": "wger", + "name": "Wger Workout Manager", + "description": "Self-hosted fitness tracker with workout logging, weight tracking, and nutrition planning. Integration with PMOVES.AI event-driven architecture for health metrics.", + "variables": [ + { + "key": "WGER_ADMIN_PASSWORD", + "file": "pmoves/env.shared", + "prompt": "Wger Django admin password", + "help": "Password for the Django superuser account at http://localhost:8000/admin/. Auto-generated as base64-encoded 16-byte random value.", + "required": true, + "sensitive": true, + "generate": { + "type": "random_bytes_base64", + "length": 16 + } + }, + { + "key": "WGER_API_TOKEN", + "file": "pmoves/env.shared", + "prompt": "Wger REST API token", + "help": "Django REST Framework token for API access. Must be generated from the Wger admin UI at http://localhost:8000/api/v2/token/. Set to GENERATE_FROM_WGER_UI as placeholder.", + "required": true, + "sensitive": true + }, + { + "key": "WGER_DB_PASSWORD", + "file": "pmoves/env.shared", + "prompt": "Wger PostgreSQL database password", + "help": "Password for the wger PostgreSQL user.", + "required": true, + "sensitive": true, + "generate": { + "type": "random_urlsafe", + "length": 32 + } + }, + { + "key": "WGER_SECRET_KEY", + "file": "pmoves/env.shared", + "prompt": "Wger Django secret key", + "help": "Django SECRET_KEY for cryptographic signing. Generate: openssl rand -base64 48", + "required": true, + "sensitive": true, + "generate": { + "type": "random_urlsafe", + "length": 64 + } + }, + { + "key": "WGER_ENABLE_REGISTRATION", + "file": "pmoves/env.shared", + "prompt": "Allow public user registration", + "help": "Set to 'true' to allow public user registration, 'false' to disable.", + "required": false, + "default": "false", + "type": "boolean" + }, + { + "key": "WGER_ENABLE_NATS", + "file": "pmoves/env.shared", + "prompt": "Enable NATS event publishing", + "help": "Set to 'true' to enable NATS event publishing for health metrics and workouts.", + "required": false, + "default": "true", + "type": "boolean" + }, + { + "key": "NATS_URL", + "file": "pmoves/env.shared", + "prompt": "NATS connection URL", + "default": "nats://nats:pmoves@nats:4222", + "help": "NATS server URL with authentication for event publishing.", + "required": true, + "type": "url" + } + ] } ] } \ No newline at end of file diff --git a/pmoves/docker-compose.yml b/pmoves/docker-compose.yml index faae84bd93..71245f29f5 100644 --- a/pmoves/docker-compose.yml +++ b/pmoves/docker-compose.yml @@ -2869,6 +2869,71 @@ services: retries: 3 start_period: 15s + # Wger - Fitness tracker with health metrics and workout logging + wger: + <<: *tier-api-hardened + image: ${WGER_IMAGE:-ghcr.io/powerfulmoves/pmoves-health-wger:pmoves-latest} + restart: unless-stopped + environment: + # Database configuration + - DATABASE_URL=postgres://wger:${WGER_DB_PASSWORD:-changeme}@wger-db:5432/wger + # Django configuration + - DJANGO_ALLOWED_HOSTS=* + - DJANGO_SECRET_KEY=${WGER_SECRET_KEY:-changeme} + - WGER_ENABLE_REGISTRATION=${WGER_ENABLE_REGISTRATION:-true} + # NATS configuration for event publishing + - NATS_URL=${NATS_URL:-nats://nats:pmoves@nats:4222} + - WGER_ENABLE_NATS=${WGER_ENABLE_NATS:-true} + # Admin credentials + - WGER_ADMIN_PASSWORD=${WGER_ADMIN_PASSWORD:-changeme} + # PMOVES integration + - ENABLE_OBSERVABILITY=${WGER_OBSERVABILITY:-true} + - PROMETHEUS_MULTIPROC_DIR=/tmp/prometheus + ports: + - "${WGER_PORT:-8000}:8000" + profiles: ["health", "wger"] + networks: + - pmoves_api + - pmoves_bus + - pmoves_data + depends_on: + wger-db: + condition: service_healthy + nats: + condition: service_healthy + volumes: + - wger-static:/home/wger/static + - wger-media:/home/wger/media + - wger-prometheus:/tmp/prometheus + healthcheck: + test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/v2/health/', timeout=5)"] + interval: 30s + timeout: 10s + retries: 5 + start_period: 40s + + # Wger database - PostgreSQL backend for fitness data + wger-db: + <<: *tier-data-hardened + image: postgres:15-alpine + restart: unless-stopped + environment: + - POSTGRES_DB=wger + - POSTGRES_USER=wger + - POSTGRES_PASSWORD=${WGER_DB_PASSWORD:-changeme} + - PGDATA=/var/lib/postgresql/data/pgdata + volumes: + - wger-db:/var/lib/postgresql/data + profiles: ["health", "wger"] + networks: + - pmoves_data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U wger -d wger"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + # Comfy Watcher - ComfyUI output watcher for NATS integration comfy-watcher: build: @@ -3335,6 +3400,11 @@ volumes: comfy-watcher-output: {} comfy-watcher-state: {} llama-results: {} + # Wger fitness tracker volumes + wger-db: {} + wger-static: {} + wger-media: {} + wger-prometheus: {} networks: pmoves_data: name: pmoves_data diff --git a/pmoves/integrations/health-wger/chit_schemas/chit.cgp.v1.0.schema.json b/pmoves/integrations/health-wger/chit_schemas/chit.cgp.v1.0.schema.json new file mode 100644 index 0000000000..afc7299fce --- /dev/null +++ b/pmoves/integrations/health-wger/chit_schemas/chit.cgp.v1.0.schema.json @@ -0,0 +1,334 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://pmoves.ai/schemas/chit.cgp.v1.0.schema.json", + "title": "CHIT Geometry Packet (CGP) v1.0", + "description": "Geometric protocol for information encoding with holographic compression and provenance tracking", + "type": "object", + "required": ["spec", "meta", "super_nodes"], + "properties": { + "spec": { + "type": "string", + "const": "chit.cgp.v1.0", + "description": "Protocol version identifier" + }, + "meta": { + "type": "object", + "description": "Metadata about the CGP packet", + "required": ["source", "units_mode", "K", "bins", "backend"], + "properties": { + "source": { + "type": "string", + "enum": ["docx", "text", "latent", "image", "audio", "video"], + "description": "Content source type" + }, + "units_mode": { + "type": "string", + "enum": ["paragraphs", "sentences", "tokens", "frames", "samples"], + "description": "Granularity of content units" + }, + "K": { + "type": "integer", + "minimum": 1, + "description": "Number of constellations (typically 4-16)" + }, + "bins": { + "type": "integer", + "minimum": 1, + "description": "Spectrum resolution (typically 5-12)" + }, + "backend": { + "type": "string", + "description": "Embedding model used" + }, + "mhep": { + "type": "number", + "description": "Multi-scale Hyperbolic Entropy Product" + }, + "Hg_traj": { + "type": "array", + "items": {"type": "number"}, + "description": "Global entropy trajectory" + }, + "Hs_traj": { + "type": "array", + "items": {"type": "number"}, + "description": "Slab entropy trajectory" + }, + "created_at": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp of creation" + }, + "encoder_version": { + "type": "string", + "description": "Encoder software version" + }, + "zeta_filtering": { + "type": "boolean", + "description": "Whether Zeta spectral filtering was applied" + } + } + }, + "sig": { + "type": "object", + "description": "HMAC-SHA256 signature for verification", + "required": ["alg", "kid", "ts", "hmac"], + "properties": { + "alg": { + "type": "string", + "const": "HMAC-SHA256", + "description": "Signature algorithm" + }, + "kid": { + "type": "string", + "minLength": 16, + "maxLength": 32, + "description": "Key identifier" + }, + "ts": { + "type": "integer", + "description": "Unix timestamp of signature" + }, + "hmac": { + "type": "string", + "description": "Base64-encoded HMAC signature" + } + } + }, + "super_nodes": { + "type": "array", + "description": "Super nodes containing constellations", + "items": { + "type": "object", + "required": ["id", "constellations"], + "properties": { + "id": { + "type": "string", + "description": "Unique super node identifier" + }, + "label": { + "type": "string", + "description": "Human-readable label" + }, + "summary": { + "type": "string", + "description": "Semantic cluster description" + }, + "x": { + "type": "number", + "description": "2D layout X coordinate (PCA/UMAP)" + }, + "y": { + "type": "number", + "description": "2D layout Y coordinate (PCA/UMAP)" + }, + "r": { + "type": "number", + "description": "Radius for visualization" + }, + "hyperbolic": { + "type": "object", + "description": "Poincaré disk encoding", + "properties": { + "poincare": { + "type": "array", + "items": {"type": "number"}, + "minItems": 2, + "maxItems": 2, + "description": "Poincaré disk coordinates [x, y]" + }, + "curvature": { + "type": "number", + "const": -1.0, + "description": "Hyperbolic curvature (fixed at -1.0)" + } + } + }, + "constellations": { + "type": "array", + "description": "Geometric constellations", + "items": { + "type": "object", + "required": ["id", "anchor", "radial_minmax", "spectrum"], + "properties": { + "id": { + "type": "string", + "description": "Unique constellation identifier" + }, + "label": { + "type": "string", + "description": "Constellation label" + }, + "summary": { + "type": "string", + "description": "Topic keywords or semantic summary" + }, + "anchor": { + "type": "array", + "items": {"type": "number"}, + "minItems": 1, + "description": "Anchor direction (unit vector in embedding space)" + }, + "radial_minmax": { + "type": "array", + "items": {"type": "number"}, + "minItems": 2, + "maxItems": 2, + "description": "Radial bounds along anchor [min, max]" + }, + "spectrum": { + "type": "array", + "items": {"type": "number", "minimum": 0}, + "description": "Energy spectrum (histogram over radial bins)" + }, + "spectrum_zeta": { + "type": "array", + "items": {"type": "number", "minimum": 0}, + "description": "Zeta-filtered spectrum" + }, + "points": { + "type": "array", + "description": "Content points (optional for geometry-only mode)", + "items": { + "type": "object", + "required": ["id"], + "properties": { + "id": { + "type": "string", + "description": "Unique point identifier" + }, + "x": { + "type": "number", + "description": "2D visualization X coordinate" + }, + "y": { + "type": "number", + "description": "2D visualization Y coordinate" + }, + "proj": { + "type": "number", + "description": "Projection onto anchor" + }, + "conf": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Assignment confidence (max p_ij)" + }, + "text": { + "type": "string", + "description": "Original unit text" + }, + "text_b64": { + "type": "string", + "description": "Base64 encoded text" + }, + "char_len": { + "type": "integer", + "minimum": 0, + "description": "Character length" + }, + "word_count": { + "type": "integer", + "minimum": 0, + "description": "Word count" + }, + "embedding": { + "type": "array", + "items": {"type": "number"}, + "description": "Raw embedding vector" + }, + "contributor_id": { + "type": "string", + "description": "Contributor identifier for attribution" + }, + "merkle_proof": { + "type": "array", + "items": {"type": "string"}, + "description": "Merkle proof for tamper evidence" + }, + "weight": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Attribution weight" + } + } + } + }, + "maca_consensus": { + "type": "object", + "description": "MACA (Multi-Agent Constellation Attribution) consensus", + "properties": { + "entropy_delta": { + "type": "number", + "description": "Entropy change from consensus" + }, + "votes": { + "type": "array", + "items": {"type": "integer", "minimum": 0}, + "description": "Vote counts per option" + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1, + "description": "Consensus confidence level" + } + } + }, + "anchor_enc": { + "type": "object", + "description": "AES-GCM encrypted anchor", + "required": ["alg", "iv", "salt", "ct"], + "properties": { + "alg": { + "type": "string", + "const": "AES-GCM", + "description": "Encryption algorithm" + }, + "iv": { + "type": "string", + "description": "Base64-encoded initialization vector" + }, + "salt": { + "type": "string", + "description": "Base64-encoded salt" + }, + "ct": { + "type": "string", + "description": "Base64-encoded ciphertext" + } + } + } + } + } + } + } + } + }, + "nats": { + "type": "object", + "description": "NATS publishing metadata", + "properties": { + "subject": { + "type": "string", + "description": "NATS subject for publishing" + }, + "timestamp": { + "type": "string", + "format": "date-time", + "description": "ISO 8601 timestamp" + }, + "publisher_id": { + "type": "string", + "description": "Publisher identifier" + }, + "stream": { + "type": "string", + "description": "JetStream stream name" + } + } + } + } +} diff --git a/pmoves/integrations/health-wger/compose/docker-compose.hardened.yml b/pmoves/integrations/health-wger/compose/docker-compose.hardened.yml new file mode 100644 index 0000000000..5ac95a3b50 --- /dev/null +++ b/pmoves/integrations/health-wger/compose/docker-compose.hardened.yml @@ -0,0 +1,53 @@ +# ============================================================================= +# PMOVES-Health-wger - Hardened Security Overlay +# ============================================================================= +# +# This compose file applies additional hardening on top of the base wger service +# defined in pmoves/docker-compose.yml. It implements read-only root filesystem +# and tmpfs mounts for maximum security. +# +# Usage: +# docker compose -f pmoves/docker-compose.yml -f pmoves/integrations/health-wger/compose/docker-compose.hardened.yml --profile wger up -d +# +# Security Features: +# - read_only: true - Prevents modification of container rootfs +# - tmpfs mounts - Isolates writable directories to RAM +# - No privileged operations - All capabilities dropped except NET_BIND_SERVICE +# +# ============================================================================= + +version: '3.8' + +services: + wger: + # Read-only root filesystem (prevents modification of container image) + read_only: true + + # Tmpfs mounts for directories that require write access + tmpfs: + # Django cache and session data + - /tmp:rw,noexec,nosuid,size=100m + # Python multiprocessing directory for Prometheus metrics + - /var/run:rw,noexec,nosuid,size=50m + # Django static files (served from here in production) + - /home/wger/static:rw,noexec,nosuid,size=200m + # Django uploaded media files + - /home/wger/media:rw,noexec,nosuid,size=500m + # Prometheus multiprocess metrics directory + - /tmp/prometheus:rw,noexec,nosuid,size=50m + + # Override entrypoint to ensure tmpfs directories exist + entrypoint: ["/bin/sh", "-c"] + command: + - | + # Create necessary directories in tmpfs + mkdir -p /tmp/prometheus + chmod 755 /tmp/prometheus + + # Start the application + exec /home/wger/entrypoint.sh + + wger-db: + # PostgreSQL requires read-write access to data directory + # No additional hardening applied - database service needs write access + # Security is handled by tier-data-hardened anchor in main compose diff --git a/pmoves/integrations/health-wger/tools/validate_cgp.py b/pmoves/integrations/health-wger/tools/validate_cgp.py new file mode 100644 index 0000000000..d6061da60a --- /dev/null +++ b/pmoves/integrations/health-wger/tools/validate_cgp.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +""" +CHIT CGP Validation Tool for PMOVES Health Integration + +Validates CGP (CHIT Geometry Packet) payloads against the v1.0 schema. +Used for ensuring health constellation data complies with PMOVES.AI's +mathematical framework standards. + +Usage: + python validate_cgp.py + python validate_cgp.py --test # Run with test payload + +Exit codes: + 0 - Validation successful + 1 - Validation failed + 2 - File/IO error +""" + +import json +import sys +from pathlib import Path +from typing import Any, Dict + +try: + import jsonschema + from jsonschema import validate, ValidationError +except ImportError: + print("Error: jsonschema not installed. Run: pip install jsonschema") + sys.exit(2) + + +def load_schema(schema_path: Path) -> Dict[str, Any]: + """Load the CGP v1.0 JSON schema.""" + if not schema_path.exists(): + raise FileNotFoundError(f"Schema not found: {schema_path}") + + with open(schema_path, 'r') as f: + return json.load(f) + + +def validate_cgp(payload: Dict[str, Any], schema: Dict[str, Any]) -> bool: + """ + Validate a CGP payload against the schema. + + Args: + payload: CGP payload dictionary + schema: JSON schema for validation + + Returns: + True if validation passes, False otherwise + """ + try: + validate(instance=payload, schema=schema) + return True + except ValidationError as e: + print(f"Validation Error: {e.message}") + print(f"Path: {'.'.join(str(p) for p in e.path)}") + print(f"Schema path: {'.'.join(str(p) for p in e.schema_path)}") + return False + + +def create_test_payload() -> Dict[str, Any]: + """Create a minimal valid CGP payload for testing.""" + return { + "spec": "chit.cgp.v1.0", + "meta": { + "source": "text", + "units_mode": "sentences", + "K": 2, + "bins": 8, + "backend": "sentence-transformers/all-MiniLM-L6-v2", + "created_at": "2026-03-13T12:00:00Z", + "encoder_version": "1.0.0" + }, + "super_nodes": [ + { + "id": "super_0", + "label": "Workout Intensity", + "summary": "Exercise intensity clusters", + "x": -100.0, + "y": 50.0, + "constellations": [ + { + "id": "const_0_0", + "label": "High Intensity", + "summary": "Vigorous exercise sessions", + "anchor": [0.1, -0.3, 0.8, 0.5], + "radial_minmax": [-0.5, 0.9], + "spectrum": [0.1, 0.15, 0.2, 0.15, 0.12, 0.1, 0.1, 0.08] + } + ] + } + ] + } + + +def main(): + """Main entry point.""" + import argparse + + parser = argparse.ArgumentParser( + description="Validate CGP payloads against CHIT v1.0 schema" + ) + parser.add_argument( + "payload", + nargs="?", + help="Path to CGP payload JSON file" + ) + parser.add_argument( + "--test", + action="store_true", + help="Run validation with test payload" + ) + parser.add_argument( + "--schema", + type=str, + default=None, + help="Custom schema path (default: ../chit_schemas/chit.cgp.v1.0.schema.json)" + ) + + args = parser.parse_args() + + # Determine schema path + if args.schema: + schema_path = Path(args.schema) + else: + script_dir = Path(__file__).parent + schema_path = script_dir.parent / "chit_schemas" / "chit.cgp.v1.0.schema.json" + + # Load schema + try: + schema = load_schema(schema_path) + print(f"Loaded schema: {schema_path}") + except FileNotFoundError as e: + print(f"Error: {e}", file=sys.stderr) + sys.exit(2) + + # Load or create payload + if args.test: + print("Using test payload...") + payload = create_test_payload() + elif args.payload: + payload_path = Path(args.payload) + try: + with open(payload_path, 'r') as f: + payload = json.load(f) + print(f"Loaded payload: {payload_path}") + except FileNotFoundError: + print(f"Error: Payload file not found: {payload_path}", file=sys.stderr) + sys.exit(2) + except json.JSONDecodeError as e: + print(f"Error: Invalid JSON in payload: {e}", file=sys.stderr) + sys.exit(2) + else: + parser.print_help() + sys.exit(2) + + # Validate + print("\nValidating CGP payload...") + if validate_cgp(payload, schema): + print("[OK] Validation PASSED") + print(f" - spec: {payload.get('spec')}") + print(f" - source: {payload.get('meta', {}).get('source')}") + print(f" - K: {payload.get('meta', {}).get('K')} constellations") + print(f" - super_nodes: {len(payload.get('super_nodes', []))}") + sys.exit(0) + else: + print("[FAIL] Validation FAILED") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/pmoves/scripts/fetch_credentials.sh b/pmoves/scripts/fetch_credentials.sh index ec78cd673b..abbb7b7845 100755 --- a/pmoves/scripts/fetch_credentials.sh +++ b/pmoves/scripts/fetch_credentials.sh @@ -228,7 +228,7 @@ done # Write environment-sourced credentials to env.shared # These are the main API keys for LLM providers -TARGET_KEYS=("OPENAI_API_KEY" "ANTHROPIC_API_KEY" "GROQ_API_KEY" "GEMINI_API_KEY" "GOOGLE_API_KEY" "MISTRAL_API_KEY" "DEEPSEEK_API_KEY" "OPENROUTER_API_KEY" "XAI_API_KEY" "ELEVENLABS_API_KEY" "VOYAGE_API_KEY" "COHERE_API_KEY" "FIREWORKS_AI_API_KEY" "PERPLEXITYAI_API_KEY" "TOGETHER_AI_API_KEY" "Z_AI_API_KEY" "ALIBABA_PRO_CODING_PLAN" "VENICE_API_KEY" "CLOUDFLARE_API_TOKEN" "CLOUDFLARE_ACCOUNT_ID" "OLLAMA_CLOUD_API_KEY") +TARGET_KEYS=("OPENAI_API_KEY" "ANTHROPIC_API_KEY" "GROQ_API_KEY" "GEMINI_API_KEY" "GOOGLE_API_KEY" "MISTRAL_API_KEY" "DEEPSEEK_API_KEY" "OPENROUTER_API_KEY" "XAI_API_KEY" "ELEVENLABS_API_KEY" "VOYAGE_API_KEY" "COHERE_API_KEY" "FIREWORKS_AI_API_KEY" "PERPLEXITYAI_API_KEY" "TOGETHER_AI_API_KEY" "Z_AI_API_KEY" "ALIBABA_PRO_CODING_PLAN" "VENICE_API_KEY" "CLOUDFLARE_API_TOKEN" "CLOUDFLARE_ACCOUNT_ID" "OLLAMA_CLOUD_API_KEY" "WGER_ADMIN_PASSWORD") # Check env.tier-llm for LLM provider keys for key in "${TARGET_KEYS[@]}"; do diff --git a/pmoves/tests/test_wger_cgp_validation.py b/pmoves/tests/test_wger_cgp_validation.py new file mode 100644 index 0000000000..8b7da9fab4 --- /dev/null +++ b/pmoves/tests/test_wger_cgp_validation.py @@ -0,0 +1,283 @@ +""" +Unit tests for CHIT CGP validation in PMOVES Health integration. + +Tests CGP schema compliance and validation tool functionality. +""" + +import json +import pytest +from pathlib import Path + +# Add integrations directory to path for imports +import sys +sys.path.insert(0, str(Path(__file__).parent.parent / "integrations" / "health-wger" / "tools")) + +from validate_cgp import validate_cgp, load_schema, create_test_payload + + +class TestCGPSchemaValidation: + """Test CGP v1.0 schema validation.""" + + @pytest.fixture + def schema_path(self): + """Path to CGP schema.""" + return Path(__file__).parent.parent / "integrations" / "health-wger" / "chit_schemas" / "chit.cgp.v1.0.schema.json" + + @pytest.fixture + def schema(self, schema_path): + """Load and return CGP schema.""" + return load_schema(schema_path) + + def test_schema_exists(self, schema_path): + """Test that schema file exists.""" + assert schema_path.exists(), f"Schema file not found: {schema_path}" + + def test_schema_valid_json(self, schema): + """Test that schema is valid JSON.""" + assert isinstance(schema, dict) + assert "$schema" in schema + assert schema["$schema"] == "http://json-schema.org/draft-07/schema#" + + def test_schema_spec_version(self, schema): + """Test that schema enforces CGP v1.0 spec.""" + assert schema["properties"]["spec"]["const"] == "chit.cgp.v1.0" + + def test_valid_test_payload(self, schema): + """Test validation of valid test payload.""" + payload = create_test_payload() + assert validate_cgp(payload, schema) is True + + def test_missing_spec_field(self, schema): + """Test that missing 'spec' field fails validation.""" + payload = create_test_payload() + del payload["spec"] + assert validate_cgp(payload, schema) is False + + def test_invalid_spec_version(self, schema): + """Test that wrong spec version fails validation.""" + payload = create_test_payload() + payload["spec"] = "chit.cgp.v0.2" + assert validate_cgp(payload, schema) is False + + def test_missing_meta_field(self, schema): + """Test that missing 'meta' field fails validation.""" + payload = create_test_payload() + del payload["meta"] + assert validate_cgp(payload, schema) is False + + def test_missing_super_nodes(self, schema): + """Test that missing 'super_nodes' field fails validation.""" + payload = create_test_payload() + del payload["super_nodes"] + assert validate_cgp(payload, schema) is False + + def test_invalid_source_enum(self, schema): + """Test that invalid source enum fails validation.""" + payload = create_test_payload() + payload["meta"]["source"] = "invalid_source" + assert validate_cgp(payload, schema) is False + + def test_valid_source_types(self, schema): + """Test all valid source types.""" + valid_sources = ["docx", "text", "latent", "image", "audio", "video"] + for source in valid_sources: + payload = create_test_payload() + payload["meta"]["source"] = source + assert validate_cgp(payload, schema), f"Failed for source: {source}" + + def test_invalid_units_mode(self, schema): + """Test that invalid units_mode fails validation.""" + payload = create_test_payload() + payload["meta"]["units_mode"] = "invalid_mode" + assert validate_cgp(payload, schema) is False + + def test_valid_units_modes(self, schema): + """Test all valid units modes.""" + valid_modes = ["paragraphs", "sentences", "tokens", "frames", "samples"] + for mode in valid_modes: + payload = create_test_payload() + payload["meta"]["units_mode"] = mode + assert validate_cgp(payload, schema), f"Failed for mode: {mode}" + + def test_missing_required_constellation_fields(self, schema): + """Test that missing required constellation fields fail validation.""" + payload = create_test_payload() + + # Remove anchor + payload["super_nodes"][0]["constellations"][0].pop("anchor", None) + assert validate_cgp(payload, schema) is False + + def test_signature_structure(self, schema): + """Test optional signature field structure.""" + payload = create_test_payload() + payload["sig"] = { + "alg": "HMAC-SHA256", + "kid": "key-identifier-16chars", + "ts": 1739001600, + "hmac": "base64-encoded-hmac" + } + assert validate_cgp(payload, schema) is True + + def test_invalid_signature_algorithm(self, schema): + """Test that invalid signature algorithm fails validation.""" + payload = create_test_payload() + payload["sig"] = { + "alg": "INVALID-ALG", + "kid": "key-id", + "ts": 1739001600, + "hmac": "base64-hmac" + } + assert validate_cgp(payload, schema) is False + + def test_encryption_structure(self, schema): + """Test optional anchor encryption field structure.""" + payload = create_test_payload() + payload["super_nodes"][0]["constellations"][0]["anchor_enc"] = { + "alg": "AES-GCM", + "iv": "base64-iv", + "salt": "base64-salt", + "ct": "base64-ciphertext" + } + assert validate_cgp(payload, schema) is True + + def test_nats_metadata(self, schema): + """Test optional NATS metadata field.""" + payload = create_test_payload() + payload["nats"] = { + "subject": "tokenism.geometry.event.v1", + "timestamp": "2026-03-13T12:00:00Z", + "publisher_id": "health-wger-publisher", + "stream": "GEOMETRY_CGP" + } + assert validate_cgp(payload, schema) is True + + def test_content_points_optional(self, schema): + """Test that content points are optional (geometry-only mode).""" + payload = create_test_payload() + # Remove points field if exists + payload["super_nodes"][0]["constellations"][0].pop("points", None) + assert validate_cgp(payload, schema) is True + + def test_minimal_valid_payload(self, schema): + """Test minimal valid CGP payload (geometry-only mode).""" + payload = { + "spec": "chit.cgp.v1.0", + "meta": { + "source": "text", + "units_mode": "sentences", + "K": 1, + "bins": 5, + "backend": "test-model" + }, + "super_nodes": [ + { + "id": "super_0", + "constellations": [ + { + "id": "const_0_0", + "anchor": [0.5, 0.5], + "radial_minmax": [0.0, 1.0], + "spectrum": [0.2, 0.2, 0.2, 0.2, 0.2] + } + ] + } + ] + } + assert validate_cgp(payload, schema) is True + + +class TestHealthConstellationExamples: + """Test health-specific constellation examples.""" + + @pytest.fixture + def schema(self): + """Load CGP schema.""" + schema_path = Path(__file__).parent.parent / "integrations" / "health-wger" / "chit_schemas" / "chit.cgp.v1.0.schema.json" + return load_schema(schema_path) + + def test_workout_constellation_example(self, schema): + """Test example workout constellation CGP.""" + payload = { + "spec": "chit.cgp.v1.0", + "meta": { + "source": "latent", + "units_mode": "workouts", + "K": 3, + "bins": 8, + "backend": "sentence-transformers/all-MiniLM-L6-v2", + "created_at": "2026-03-13T12:00:00Z" + }, + "super_nodes": [ + { + "id": "workout_intensity", + "label": "Workout Intensity", + "summary": "Exercise intensity clustering", + "constellations": [ + { + "id": "high_intensity", + "label": "High Intensity", + "summary": "Vigorous exercise sessions", + "anchor": [0.2, -0.4, 0.7, 0.5], + "radial_minmax": [-0.3, 0.8], + "spectrum": [0.05, 0.1, 0.15, 0.25, 0.2, 0.15, 0.08, 0.02] + }, + { + "id": "moderate_intensity", + "label": "Moderate Intensity", + "summary": "Moderate exercise sessions", + "anchor": [0.1, 0.3, -0.2, 0.9], + "radial_minmax": [-0.5, 0.5], + "spectrum": [0.1, 0.12, 0.15, 0.18, 0.18, 0.15, 0.08, 0.04] + }, + { + "id": "low_intensity", + "label": "Low Intensity", + "summary": "Light exercise sessions", + "anchor": [-0.3, 0.5, 0.2, 0.8], + "radial_minmax": [-0.6, 0.3], + "spectrum": [0.15, 0.18, 0.2, 0.18, 0.15, 0.08, 0.04, 0.02] + } + ] + } + ] + } + assert validate_cgp(payload, schema) is True + + def test_weight_progression_constellation(self, schema): + """Test example weight progression constellation CGP.""" + payload = { + "spec": "chit.cgp.v1.0", + "meta": { + "source": "text", + "units_mode": "measurements", + "K": 2, + "bins": 6, + "backend": "sentence-transformers/all-MiniLM-L6-v2" + }, + "super_nodes": [ + { + "id": "weight_trends", + "label": "Weight Progression", + "summary": "Weight change patterns over time", + "constellations": [ + { + "id": "weight_loss", + "label": "Weight Loss", + "summary": "Periods of weight reduction", + "anchor": [0.4, -0.6, 0.7], + "radial_minmax": [0.0, 0.9], + "spectrum": [0.1, 0.15, 0.25, 0.25, 0.15, 0.1] + }, + { + "id": "weight_gain", + "label": "Weight Gain", + "summary": "Periods of weight increase", + "anchor": [-0.5, 0.4, 0.7], + "radial_minmax": [-0.2, 0.7], + "spectrum": [0.15, 0.2, 0.25, 0.2, 0.15, 0.05] + } + ] + } + ] + } + assert validate_cgp(payload, schema) is True diff --git a/pmoves/tools/brand_defaults.py b/pmoves/tools/brand_defaults.py index d970663166..cc13420ff2 100644 --- a/pmoves/tools/brand_defaults.py +++ b/pmoves/tools/brand_defaults.py @@ -142,6 +142,13 @@ def _ensure_integration_credentials(text: str) -> str: if _is_blank_or_placeholder(wger_token): text = _set_kv(text, "WGER_API_TOKEN", "GENERATE_FROM_WGER_UI") + # Wger admin password: Django superuser password for the wger admin panel. + # Base64-encoded 16-byte random value for security. + wger_admin_pass = _get_kv(text, "WGER_ADMIN_PASSWORD") + if _is_blank_or_placeholder(wger_admin_pass): + wger_admin_pass = base64.b64encode(secrets.token_bytes(16)).decode("utf-8") + text = _set_kv(text, "WGER_ADMIN_PASSWORD", wger_admin_pass) + return text