trusty-mpm 1.7.0

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
# Environment Validation Workflows

> **Part of**: [env-manager]../SKILL.md
> **Category**: infrastructure
> **Reading Level**: Intermediate

## Purpose

Complete validation workflows for environment variables: structure checks, completeness verification, naming conventions, and framework-specific validation patterns.

## Validation Hierarchy

### Level 1: Structure Validation (Basic)
Validates file format and syntax.

### Level 2: Semantic Validation (Intermediate)
Validates naming, completeness, framework conventions.

### Level 3: Integration Validation (Advanced)
Validates across environments, platforms, and services.

## Structure Validation

### Check 1: Valid Key-Value Format

**What to Check:**
```bash
# Valid formats:
KEY=value
KEY="value with spaces"
KEY='single quoted'
KEY=

# Invalid formats:
key=value              # lowercase
KEY = value            # spaces around =
KEY=value # comment    # inline comments (parser-dependent)
=value                 # missing key
KEY                    # missing =
```

**Validation Script:**
```python
import re
from pathlib import Path

def validate_structure(env_file: Path) -> list[str]:
    """Validate .env file structure."""
    errors = []
    valid_line_pattern = re.compile(r'^[A-Z_][A-Z0-9_]*=.*$')

    with open(env_file) as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()

            # Skip empty lines and comments
            if not line or line.startswith('#'):
                continue

            # Check format
            if not valid_line_pattern.match(line):
                errors.append(f"Line {line_num}: Invalid format: {line}")

            # Check for inline comments (warning)
            if '#' in line and not line.startswith('#'):
                # Check if # is inside quotes
                key, value = line.split('=', 1)
                if '#' in value and not (value.startswith('"') or value.startswith("'")):
                    errors.append(f"Line {line_num}: WARNING: Possible inline comment: {line}")

    return errors
```

### Check 2: No Duplicate Keys

**Issue:**
```bash
# .env file
DATABASE_URL=postgres://local
DATABASE_URL=postgres://production  # Duplicate! Which wins?
```

**Validation:**
```python
def check_duplicates(env_file: Path) -> dict[str, list[int]]:
    """Find duplicate keys and their line numbers."""
    keys = {}

    with open(env_file) as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith('#'):
                continue

            if '=' in line:
                key = line.split('=', 1)[0]
                if key in keys:
                    keys[key].append(line_num)
                else:
                    keys[key] = [line_num]

    # Return only duplicates
    return {k: v for k, v in keys.items() if len(v) > 1}
```

### Check 3: Proper Quoting

**Valid Quoting Patterns:**
```bash
# No quotes needed
SIMPLE_VALUE=hello

# Quotes required for spaces
WITH_SPACES="hello world"

# Quotes required for special chars
SPECIAL_CHARS="value with = or # chars"

# Escape quotes inside quotes
ESCAPED="He said \"hello\""
ESCAPED_SINGLE='It'\''s working'
```

**Validation:**
```python
def validate_quoting(env_file: Path) -> list[str]:
    """Check for proper quoting."""
    warnings = []

    with open(env_file) as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith('#') or '=' not in line:
                continue

            key, value = line.split('=', 1)

            # Check for spaces without quotes
            if ' ' in value and not (value.startswith('"') or value.startswith("'")):
                warnings.append(f"Line {line_num}: Value with spaces should be quoted: {key}")

            # Check for special chars without quotes
            if any(char in value for char in ['#', '=', '$']) and not value.startswith(('"', "'")):
                warnings.append(f"Line {line_num}: Value with special chars should be quoted: {key}")

    return warnings
```

## Completeness Validation

### Compare Against .env.example

**Workflow:**
```python
def compare_env_files(env_file: Path, example_file: Path) -> dict:
    """Compare .env against .env.example."""

    def parse_keys(file_path: Path) -> set[str]:
        keys = set()
        with open(file_path) as f:
            for line in f:
                line = line.strip()
                if line and not line.startswith('#') and '=' in line:
                    key = line.split('=', 1)[0]
                    keys.add(key)
        return keys

    env_keys = parse_keys(env_file)
    example_keys = parse_keys(example_file)

    return {
        'missing': example_keys - env_keys,  # Required but missing
        'extra': env_keys - example_keys,    # Present but not documented
        'common': env_keys & example_keys    # Properly documented
    }
```

**Usage:**
```bash
# Find missing required variables
python validate_env.py .env --compare .env.example

# Output:
# Missing variables (in .env.example but not .env):
#   - DATABASE_URL
#   - JWT_SECRET
#   - SMTP_HOST
#
# Extra variables (in .env but not documented):
#   - DEBUG_MODE
#   - TEMP_API_KEY
```

### Check Required Variables by Environment

**Pattern:**
```python
REQUIRED_VARS = {
    'development': [
        'NODE_ENV',
        'DATABASE_URL',
        'PORT'
    ],
    'production': [
        'NODE_ENV',
        'DATABASE_URL',
        'PORT',
        'JWT_SECRET',
        'API_KEY',
        'REDIS_URL'
    ],
    'test': [
        'NODE_ENV',
        'TEST_DATABASE_URL'
    ]
}

def validate_required_vars(env_file: Path, environment: str) -> list[str]:
    """Check if all required variables are present."""
    required = REQUIRED_VARS.get(environment, [])
    present = parse_keys(env_file)

    missing = [var for var in required if var not in present]
    return missing
```

## Naming Convention Validation

### Standard Conventions

**Valid Names:**
```bash
# Standard format: UPPERCASE_WITH_UNDERSCORES
DATABASE_URL=value
API_KEY=value
MAX_CONNECTIONS=10

# Framework-specific prefixes
NEXT_PUBLIC_API_URL=value       # Next.js client-side
VITE_API_URL=value              # Vite client-side
REACT_APP_API_URL=value         # Create React App
```

**Invalid Names:**
```bash
# Bad patterns
databaseUrl=value          # camelCase
database-url=value         # kebab-case
database.url=value         # dots
123_KEY=value              # starts with number
_PRIVATE_KEY=value         # leading underscore (convention warning)
```

**Validation:**
```python
import re

def validate_naming_conventions(env_file: Path, framework: str = None) -> list[str]:
    """Validate variable naming conventions."""
    errors = []

    # Standard pattern
    standard_pattern = re.compile(r'^[A-Z][A-Z0-9_]*$')

    # Framework-specific patterns
    framework_patterns = {
        'nextjs': re.compile(r'^(NEXT_PUBLIC_|NEXT_)[A-Z0-9_]+$'),
        'vite': re.compile(r'^(VITE_)?[A-Z0-9_]+$'),
        'react': re.compile(r'^(REACT_APP_)?[A-Z0-9_]+$'),
    }

    with open(env_file) as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith('#') or '=' not in line:
                continue

            key = line.split('=', 1)[0]

            # Check standard pattern
            if not standard_pattern.match(key):
                errors.append(f"Line {line_num}: Invalid naming: {key} (use UPPERCASE_WITH_UNDERSCORES)")

            # Check framework-specific patterns
            if framework and framework in framework_patterns:
                pattern = framework_patterns[framework]
                if not pattern.match(key):
                    errors.append(f"Line {line_num}: {framework} convention violation: {key}")

    return errors
```

## Framework-Specific Validation

### Next.js Validation

**Rules:**
```python
def validate_nextjs_env(env_file: Path) -> list[str]:
    """Validate Next.js environment variables."""
    errors = []
    warnings = []

    with open(env_file) as f:
        for line_num, line in enumerate(f, 1):
            line = line.strip()
            if not line or line.startswith('#') or '=' not in line:
                continue

            key, value = line.split('=', 1)

            # Check NEXT_PUBLIC_ prefix rules
            if key.startswith('NEXT_PUBLIC_'):
                # Warn about secrets in public vars
                if any(secret in key.lower() for secret in ['secret', 'key', 'password', 'token']):
                    errors.append(f"Line {line_num}: SECURITY: Secret in NEXT_PUBLIC_ var: {key}")

            # Check for client-side vars without NEXT_PUBLIC_
            if any(client in key.lower() for client in ['api_url', 'api_endpoint']):
                if not key.startswith('NEXT_PUBLIC_'):
                    warnings.append(f"Line {line_num}: Client-side var without NEXT_PUBLIC_: {key}")

    return errors, warnings
```

**File Precedence Check:**
```python
def check_nextjs_file_precedence(project_dir: Path) -> dict:
    """Check Next.js .env file precedence."""
    env_files = [
        '.env.local',
        '.env.development.local',
        '.env.production.local',
        '.env.development',
        '.env.production',
        '.env'
    ]

    found_files = []
    for env_file in env_files:
        if (project_dir / env_file).exists():
            found_files.append(env_file)

    # Parse and check for conflicts
    all_vars = {}
    for env_file in found_files:
        vars_in_file = parse_env_file(project_dir / env_file)
        for key, value in vars_in_file.items():
            if key in all_vars:
                all_vars[key].append((env_file, value))
            else:
                all_vars[key] = [(env_file, value)]

    # Find variables defined in multiple files
    conflicts = {k: v for k, v in all_vars.items() if len(v) > 1}

    return {
        'files_found': found_files,
        'conflicts': conflicts,
        'precedence_order': env_files
    }
```

### Express/Node.js Validation

**Standard Variables:**
```python
NODE_STANDARD_VARS = {
    'NODE_ENV': ['development', 'production', 'test'],
    'PORT': r'^\d+$',  # Must be a number
    'DATABASE_URL': r'^postgres://|mysql://|mongodb://',  # Must be valid connection string
}

def validate_nodejs_env(env_file: Path) -> list[str]:
    """Validate Node.js environment variables."""
    errors = []
    vars_dict = parse_env_file(env_file)

    for key, value in vars_dict.items():
        if key in NODE_STANDARD_VARS:
            expected = NODE_STANDARD_VARS[key]

            if isinstance(expected, list):
                # Check enumeration
                if value not in expected:
                    errors.append(f"{key}: Invalid value '{value}', expected one of {expected}")
            elif isinstance(expected, str):
                # Check regex pattern
                if not re.match(expected, value):
                    errors.append(f"{key}: Value doesn't match expected format")

    return errors
```

## Summary

**Validation Workflow:**
1. **Structure**: Valid format, no duplicates, proper quoting
2. **Completeness**: All required vars present, compare with .env.example
3. **Naming**: UPPERCASE_WITH_UNDERSCORES, framework prefixes
4. **Framework**: Next.js NEXT_PUBLIC_, file precedence
5. **Platform**: Vercel/Railway/Heroku conventions

**Key Validations:**
- ✅ Valid key-value format
- ✅ No duplicate keys
- ✅ Proper quoting for spaces/special chars
- ✅ All required variables present
- ✅ Consistent naming conventions
- ✅ Framework-specific rules followed
- ✅ No secrets in client-side vars (NEXT_PUBLIC_)

## Related References

- [Security]security.md: Secret scanning and exposure detection
- [Synchronization]synchronization.md: Platform sync validation
- [Frameworks]frameworks.md: Complete framework patterns

---
**Lines**: 285 ✓ 150-300 range