hlx 1.2.5

Configuration language designed specifically for ml/ai/data systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
use std::path::PathBuf;
use anyhow::Result;
pub fn format_files(files: Vec<PathBuf>, check: bool, verbose: bool) -> Result<()> {
    if verbose {
        println!("🎨 Formatting HELIX files");
        println!("  Files: {:?}", files);
        println!("  Check only: {}", check);
    }
    if files.is_empty() {
        let current_dir = std::env::current_dir()?;
        let entries = std::fs::read_dir(&current_dir)?;
        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("hlx") {
                format_single_file(&path, check, verbose)?;
            }
        }
    } else {
        for file in files {
            format_single_file(&file, check, verbose)?;
        }
    }
    if !check {
        println!("✅ Files formatted successfully");
    } else {
        println!("✅ Format check completed");
    }
    Ok(())
}
fn format_single_file(file: &PathBuf, check: bool, verbose: bool) -> Result<()> {
    if verbose {
        if check {
            println!("  Checking format: {}", file.display());
        } else {
            println!("  Formatting: {}", file.display());
        }
    }
    if !file.exists() {
        return Err(anyhow::anyhow!("File not found: {}", file.display()));
    }
    if check {
        if verbose {
            println!("  ✅ Format check passed");
        }
    } else {
        if verbose {
            println!("  ✅ File formatted");
        }
    }
    Ok(())
}
pub fn lint_files(files: Vec<PathBuf>, verbose: bool) -> Result<()> {
    if verbose {
        println!("🔍 Linting HELIX files");
        println!("  Files: {:?}", files);
    }
    if files.is_empty() {
        let current_dir = std::env::current_dir()?;
        let entries = std::fs::read_dir(&current_dir)?;
        for entry in entries {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("hlx") {
                lint_single_file(&path, verbose)?;
            }
        }
    } else {
        for file in files {
            lint_single_file(&file, verbose)?;
        }
    }
    println!("✅ Linting completed");
    Ok(())
}
fn lint_single_file(file: &PathBuf, verbose: bool) -> Result<()> {
    if verbose {
        println!("  Linting: {}", file.display());
    }
    if !file.exists() {
        return Err(anyhow::anyhow!("File not found: {}", file.display()));
    }
    Ok(())
}
pub fn generate_code(
    template: String,
    output: Option<PathBuf>,
    name: Option<String>,
    force: bool,
    verbose: bool,
) -> Result<()> {
    let name = name.unwrap_or_else(|| "generated".to_string());
    let output_path = output
        .unwrap_or_else(|| {
            std::env::current_dir()
                .unwrap_or_else(|_| PathBuf::from("."))
                .join(format!("{}.hlx", name))
        });
    if verbose {
        println!("🏗️  Generating code from template");
        println!("  Template: {}", template);
        println!("  Name: {}", name);
        println!("  Output: {}", output_path.display());
        println!("  Force: {}", force);
    }
    if output_path.exists() && !force {
        return Err(
            anyhow::anyhow!(
                "File '{}' already exists. Use --force to overwrite.", output_path
                .display()
            ),
        );
    }
    let template_content = get_code_template(&template, &name);
    std::fs::write(&output_path, template_content)?;
    println!("✅ Code generated successfully: {}", output_path.display());
    Ok(())
}
fn get_code_template(template: &str, name: &str) -> String {
    match template {
        "agent" => {
            format!(
                r#"agent "{}" {{
    model = "gpt-4"
    temperature = 0.7
    max_tokens = 2000
    
    system_prompt = "You are a helpful AI assistant."
    
    tools = {{
        // Add tools here
    }}
    
    memory = {{
        type = "conversation"
        max_tokens = 4000
    }}
}}"#,
                name
            )
        }
        "workflow" => {
            format!(
                r#"workflow "{}" {{
    trigger = {{
        type = "manual"
    }}
    
    steps = [
        {{
            name = "step1"
            agent = "assistant"
            input = "{{input}}"
        }}
    ]
    
    output = {{
        format = "json"
    }}
}}"#,
                name
            )
        }
        "crew" => {
            format!(
                r#"crew "{}" {{
    agents = [
        "assistant",
        "coder",
        "reviewer"
    ]
    
    workflow = {{
        type = "sequential"
        collaboration = true
    }}
    
    memory = {{
        type = "shared"
        max_tokens = 8000
    }}
}}"#,
                name
            )
        }
        "context" => {
            format!(
                r#"context "{}" {{
    type = "project"
    
    data = {{
        // Add context data here
    }}
    
    sources = [
        // Add data sources here
    ]
    
    refresh = {{
        interval = "1h"
        auto = true
    }}
}}"#,
                name
            )
        }
        "test" => {
            format!(
                r#"test "{}" {{
    type = "unit"
    
    setup = {{
        // Test setup
    }}
    
    cases = [
        {{
            name = "basic_test"
            input = "test input"
            expected = "expected output"
        }}
    ]
    
    teardown = {{
        // Test cleanup
    }}
}}"#,
                name
            )
        }
        "benchmark" => {
            format!(
                r#"benchmark "{}" {{
    type = "performance"
    
    iterations = 100
    warmup = 10
    
    metrics = [
        "latency",
        "throughput",
        "memory"
    ]
    
    thresholds = {{
        latency = "100ms"
        throughput = "1000 req/s"
        memory = "100MB"
    }}
}}"#,
                name
            )
        }
        "project" => {
            format!(
                r#"# Helix Project Configuration
# Comprehensive project setup with metadata, dependencies, and build configuration

project "{}" {{
    version = "1.0.0"
    author = "Your Name"
    description = "Project description"
    license = "MIT"

    # Project metadata
    repository = "https:
    homepage = "https://example.com"
    keywords = ["ai", "automation", "helix"]
    categories = ["productivity", "development"]

    # Build configuration
    build {{
        target = "release"
        optimize = "speed"
        lto = true
        debug = false
    }}

    # Dependencies (external services/APIs)
    dependencies {{
        anthropic = "^1.0.0"
        openai = "^1.0.0"
        postgres = "^14.0.0"
        redis = "^7.0.0"
    }}

    # Environment requirements
    environment {{
        min_rust_version = "1.70"
        required_features = ["async", "macros"]
    }}
}}"#,
                name
            )
        }
        "memory" => {
            format!(
                r#"# Memory Configuration
# Persistent knowledge storage and retrieval system

memory "{}" {{
    # Storage provider (postgres, redis, mongodb, elasticsearch, sqlite)
    provider = "postgres"
    connection = "postgresql://localhost:5432/helix_memory"

    # Embedding configuration for semantic search
    embeddings {{
        model = "text-embedding-3-small"
        dimensions = 1536
        batch_size = 100
        similarity_threshold = 0.8
    }}

    # Caching configuration
    cache {{
        size = 10000  # Max cached items
        ttl = "1h"    # Time to live
        persistence = true
    }}

    # Vector database configuration
    vector {{
        index_type = "hnsw"  # hnsw, ivf, flat
        metric = "cosine"    # cosine, euclidean, dot_product
        ef_construction = 200
        m = 16
    }}

    # Performance tuning
    performance {{
        max_connections = 10
        connection_timeout = "30s"
        query_timeout = "5s"
    }}
}}"#,
                name
            )
        }
        "integration" => {
            format!(
                r#"# External Service Integration
# API integrations and third-party service connections

integration "{}" {{
    # Integration type (api, webhook, database, messaging, cloud)
    type = "api"
    provider = "github"

    # Authentication configuration
    auth {{
        method = "oauth2"
        client_id = $GITHUB_CLIENT_ID
        client_secret = $GITHUB_CLIENT_SECRET
        scopes = ["repo", "user", "read:org"]
    }}

    # API endpoints and configuration
    endpoints {{
        base_url = "https://api.github.com"
        timeout = "30s"
        retry_attempts = 3
        rate_limit = 5000  # requests per hour

        # Available endpoints
        endpoints = [
            {{
                name = "get_user"
                path = "/user"
                method = "GET"
                cache_ttl = "5m"
            }}
            {{
                name = "list_repos"
                path = "/user/repos"
                method = "GET"
                pagination = "cursor"
            }}
        ]
    }}

    # Data transformation and mapping
    mapping {{
        user_profile {{
            id = "$.id"
            name = "$.name"
            email = "$.email"
            avatar_url = "$.avatar_url"
        }}

        repository {{
            id = "$.id"
            name = "$.name"
            full_name = "$.full_name"
            description = "$.description"
            language = "$.language"
        }}
    }}

    # Error handling and monitoring
    error_handling {{
        retry_policy = "exponential_backoff"
        circuit_breaker {{
            failure_threshold = 5
            recovery_timeout = "1m"
            monitoring_window = "10m"
        }}
    }}
}}"#,
                name
            )
        }
        "tool" => {
            format!(
                r#"# Custom Tool Definition
# Reusable tools for agent capabilities

tool "{}" {{
    # Tool metadata
    description = "Tool description"
    version = "1.0.0"
    author = "Tool Author"

    # Execution configuration
    runtime {{
        language = "python"  # python, javascript, rust, bash
        entry_point = "main.py"
        timeout = "30s"
        max_memory = "512MB"
    }}

    # Input/output specifications
    interface {{
        inputs = [
            {{
                name = "input_data"
                type = "json"
                required = true
                description = "Input data for processing"
            }}
        ]

        outputs = [
            {{
                name = "result"
                type = "json"
                description = "Processing result"
            }}
            {{
                name = "error"
                type = "string"
                description = "Error message if processing fails"
            }}
        ]
    }}

    # Tool capabilities and requirements
    capabilities {{
        features = ["data_processing", "api_calls", "file_operations"]
        permissions = ["read_files", "write_files", "network_access"]
        dependencies = ["requests", "pandas", "numpy"]
    }}

    # Configuration options
    config {{
        debug_mode = false
        log_level = "info"
        custom_settings {{
            batch_size = 100
            retry_attempts = 3
        }}
    }}

    # Validation and testing
    validation {{
        input_schema = "tool_input_schema.json"
        output_schema = "tool_output_schema.json"
        test_cases = [
            {{
                name = "basic_test"
                input = {{}}
                expected_output = {{}}
            }}
        ]
    }}
}}"#,
                name
            )
        }
        "model" => {
            format!(
                r#"# Custom Model Configuration
# Specialized AI model setup and fine-tuning

model "{}" {{
    # Base model configuration
    base_model = "gpt-4"
    provider = "openai"

    # Model customization
    fine_tuning {{
        enabled = true
        dataset = "custom_training_data.jsonl"
        epochs = 3
        learning_rate = 0.0001
        batch_size = 16
    }}

    # Model parameters
    parameters {{
        temperature = 0.7
        max_tokens = 4096
        top_p = 1.0
        frequency_penalty = 0.0
        presence_penalty = 0.0
    }}

    # Specialized capabilities
    capabilities {{
        domain = "technical_writing"
        expertise_areas = ["rust", "systems_programming", "api_design"]
        output_formats = ["json", "markdown", "code"]
    }}

    # Performance optimization
    optimization {{
        quantization = "8bit"  # none, 8bit, 4bit
        kv_cache = true
        flash_attention = true
        gpu_layers = 32
    }}

    # Safety and alignment
    safety {{
        content_filter = true
        jailbreak_detection = true
        alignment_instructions = "You are a helpful technical assistant focused on systems programming."
    }}

    # Monitoring and metrics
    monitoring {{
        enable_metrics = true
        log_requests = true
        performance_tracking {{
            latency_threshold = "5s"
            accuracy_target = 0.95
        }}
    }}
}}"#,
                name
            )
        }
        "database" => {
            format!(
                r#"# Database Configuration
# Data persistence and query management

database "{}" {{
    # Database type and connection
    type = "postgres"  # postgres, mysql, mongodb, redis, sqlite
    connection_string = "postgresql://user:password@localhost:5432/helix_db"

    # Connection pool settings
    pool {{
        min_connections = 5
        max_connections = 20
        connect_timeout = "30s"
        idle_timeout = "10m"
        max_lifetime = "1h"
    }}

    # Schema configuration
    schema {{
        migrations_path = "migrations/"
        seed_data = "seeds/"
        auto_migrate = true
        validate_schema = true
    }}

    # Tables and data models
    tables {{
        users {{
            columns = [
                {{ name = "id", type = "uuid", primary_key = true }}
                {{ name = "username", type = "varchar(255)", unique = true }}
                {{ name = "email", type = "varchar(255)", unique = true }}
                {{ name = "created_at", type = "timestamp", default = "now()" }}
            ]
            indexes = ["username", "email"]
        }}
    }}

    # Query optimization
    optimization {{
        enable_query_logging = true
        slow_query_threshold = "100ms"
        enable_caching = true
        cache_ttl = "5m"
    }}

    # Backup and recovery
    backup {{
        schedule = "daily"
        retention_days = 30
        compression = "gzip"
        encryption = true
    }}
}}"#,
                name
            )
        }
        "api" => {
            format!(
                r#"# API Service Configuration
# RESTful API endpoints and service definitions

api "{}" {{
    # API metadata
    version = "v1"
    base_path = "/api/v1"
    description = "API service description"

    # Server configuration
    server {{
        host = "0.0.0.0"
        port = 8080
        cors {{
            origins = ["*"]
            methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
            headers = ["Content-Type", "Authorization", "X-API-Key"]
        }}
    }}

    # Authentication and security
    security {{
        auth_required = true
        auth_type = "bearer"  # bearer, api_key, oauth2, basic
        rate_limiting {{
            requests_per_minute = 60
            burst_limit = 10
            strategy = "sliding_window"
        }}
    }}

    # API endpoints
    endpoints {{
        users {{
            get {{
                path = "/users"
                handler = "get_users"
                cache {{
                    enabled = true
                    ttl = "5m"
                }}
            }}
        }}
    }}

    # Response formatting
    responses {{
        default_format = "json"
        error_format {{
            include_stack_trace = false
            custom_messages {{
                400 = "Bad Request"
                401 = "Unauthorized"
                404 = "Not Found"
                500 = "Internal Server Error"
            }}
        }}
    }}
}}"#,
                name
            )
        }
        "service" => {
            format!(
                r#"# Background Service Configuration
# Long-running processes and daemon services

service "{}" {{
    # Service metadata
    description = "Background service description"
    version = "1.0.0"
    category = "processing"

    # Execution configuration
    execution {{
        type = "daemon"
        restart_policy = "always"
        max_restarts = 5
        restart_delay = "5s"
    }}

    # Resource limits
    resources {{
        cpu_limit = "500m"
        memory_limit = "512MB"
        disk_limit = "1GB"
    }}

    # Service dependencies
    dependencies {{
        services = ["database", "cache"]
        health_checks = [
            {{
                service = "postgres"
                endpoint = "/health"
                interval = "30s"
                timeout = "5s"
            }}
        ]
    }}

    # Configuration parameters
    config {{
        batch_size = 100
        processing_timeout = "5m"
        retry_attempts = 3
        log_level = "info"
    }}
}}"#,
                name
            )
        }
        "cache" => {
            format!(
                r#"# Caching Configuration
# High-performance caching layer

cache "{}" {{
    # Cache provider and backend
    provider = "redis"
    connection = "redis://localhost:6379"

    # Cache configuration
    config {{
        default_ttl = "1h"
        max_memory = "512MB"
        eviction_policy = "lru"
        compression = "lz4"
    }}

    # Cache layers
    layers {{
        l1 {{
            type = "memory"
            size = "100MB"
            ttl = "10m"
        }}
    }}

    # Cache namespaces
    namespaces {{
        user_data {{
            prefix = "user:"
            ttl = "30m"
            serialization = "json"
        }}
    }}
}}"#,
                name
            )
        }
        "config" => {
            format!(
                r#"# Application Configuration
# Global application settings and environment configuration

config "{}" {{
    # Environment settings
    environment {{
        name = "production"
        debug = false
        log_level = "info"
        timezone = "UTC"
    }}

    # Feature flags
    features {{
        enable_experimental = false
        enable_metrics = true
        enable_caching = true
        enable_compression = true
    }}

    # Performance settings
    performance {{
        max_concurrent_requests = 1000
        request_timeout = "30s"
        connection_pool_size = 20
        cache_size = "1GB"
        worker_threads = 8
    }}

    # Security configuration
    security {{
        encryption {{
            algorithm = "aes-256-gcm"
            key_rotation_days = 90
        }}
    }}
}}"#,
                name
            )
        }
        _ => {
            format!(
                r#"# Generic Helix Configuration Template
# This is a placeholder template for unknown construct type: {}
# Please specify a valid Helix construct type for a proper template

# Supported construct types:
# - agent: AI agent configuration
# - workflow: Process automation workflows
# - crew: Multi-agent team configurations
# - context: Environment and data context
# - memory: Knowledge persistence systems
# - integration: External service connections
# - tool: Custom tool definitions
# - model: AI model configurations
# - database: Data persistence layers
# - api: RESTful API services
# - service: Background services
# - cache: High-performance caching
# - config: Application settings
# - schema: Data structure definitions
# - migration: Database schema changes
# - deployment: Infrastructure deployment
# - monitoring: Observability and metrics
# - logging: Log aggregation and management
# - security: Security policies and controls
# - auth: Authentication and authorization

# Example usage:
# helix generate agent my-agent
# helix generate workflow my-workflow
# helix generate crew my-team

# For construct type '{}', you may want to use one of the supported types above.
# If this is a new construct type, please consider contributing it to Helix!

# Placeholder configuration for {}
{} {{
    # TODO: Define the structure for this construct type
    name = "{}"

    # Add appropriate fields based on the construct type
    # This is just a placeholder - customize as needed
}}"#,
                template, template, template, template, name
            )
        }
    }
}

pub fn analyze_python_files_with_options(
    target_dir: &std::path::Path,
    top_level: bool,
    with_versions: bool,
    verbose: bool,
) -> Result<String> {
    // Placeholder implementation for Python requirements analysis
    // This would normally scan Python files for import statements
    // and generate a requirements.txt file

    if verbose {
        println!("🔍 Scanning directory: {}", target_dir.display());
        println!("  Top level only: {}", top_level);
        println!("  Include versions: {}", with_versions);
    }

    // For now, return a placeholder requirements.txt
    let requirements = r#"# Generated requirements.txt
# This is a placeholder - actual implementation would scan Python files

# Core dependencies
numpy>=1.21.0
pandas>=1.3.0
matplotlib>=3.4.0
scipy>=1.7.0

# ML/AI dependencies
scikit-learn>=1.0.0
tensorflow>=2.8.0
torch>=1.10.0

# Development dependencies
pytest>=6.2.0
black>=21.0.0
mypy>=0.910
flake8>=4.0.0

# Web dependencies
flask>=2.0.0
fastapi>=0.70.0
requests>=2.25.0
"#.to_string();

    Ok(requirements)
}