stand 0.2.1

A CLI tool for explicit environment variable management
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
# Stand - Design Document

## 1. Architecture Overview

### 1.1 High-Level Architecture

Stand follows a simple command-line application architecture with clear separation between user interface, business logic, and system interaction layers.

```mermaid
graph TB
    User([User])
    CLI[CLI Interface]
    CH[Command Handler]
    EM[Environment Manager]
    CL[Configuration Loader]
    SM[State Manager]
    ShM[Shell Manager]
    PE[Process Executor]
    FS[(File System)]
    SS[(State Storage)]
    Shell([Shell/Process])
    
    User --> CLI
    CLI --> CH
    CH --> EM
    EM --> ShM
    EM --> PE
    ShM --> Shell
    PE --> Shell
    EM --> CL
    EM --> SM
    CL --> FS
    SM --> SS
```

### 1.2 Core Components

- **CLI Interface**: Parses user commands and arguments
- **Command Handler**: Routes commands to appropriate business logic
- **Environment Manager**: Resolves and manages environment variables
- **Configuration Loader**: Reads and validates configuration files
- **Shell Manager**: Handles shell-specific operations and subshell creation
- **State Manager**: Tracks and persists application state
- **Process Executor**: Runs commands with injected environment variables

## 2. Technology Stack

### 2.1 Implementation Language

**Rust** - Chosen for:
- Memory safety without garbage collection
- Fast startup times critical for CLI tools
- Single binary distribution
- Excellent error handling with Result types
- Strong ecosystem for CLI development

### 2.2 Key Dependencies

- **clap** (v4): Command-line argument parsing with derive macros
- **serde** + **serde_yaml**: Configuration file parsing
- **anyhow**: Simplified error handling
- **colored**: Terminal output formatting
- **indexmap**: Order-preserving hash maps for environment variables
- **dirs**: Cross-platform directory paths
- **which**: Shell detection

### 2.3 Build Toolchain

- **cargo**: Build system and package manager
- **rustc**: Rust compiler with optimization flags
- **cross**: Cross-compilation for different platforms

## 3. Data Model

### 3.1 Configuration Structure

```
Configuration
├── version: String
├── environments: Map<String, Environment>
├── common: Option<Map<String, String>>
└── settings: Settings

Environment
├── description: String
├── extends: Option<String>
├── variables: Map<String, String>
├── color: Option<Color>
└── requires_confirmation: bool

Settings
├── nested_shell_behavior: NestedBehavior
└── show_env_in_prompt: bool
```

### 3.2 State Structure

```
State
├── current_environment: Option<String>
├── last_switched: Timestamp
├── session_id: String
├── parent_shell_pid: Option<ProcessId>
└── overrides: Map<String, String>
```

### 3.3 Environment Variables Model

```
EnvironmentVariables
├── common: Map<String, String>    // From common section
├── specific: Map<String, String>  // From environment section
├── inherited: Map<String, String> // From parent environment (extends)
└── session: Map<String, String>   // Runtime overrides
```

## 4. Data Flow

### 4.1 Environment Loading Flow

1. **Configuration Discovery**
   - Search for `.stand.toml` file (TOML format) in current directory
   - Validate configuration schema and structure
   - Cache parsed configuration

2. **Variable Resolution**
   - Load common variables from `[common]` section
   - Resolve environment inheritance using `extends` field
   - Load environment-specific variables
   - Apply session overrides from state
   - Merge in precedence order: common → parent → environment → session

3. **Environment Activation**
   - For subshell: Create new shell process with variables
   - For exec: Run command with temporary environment

### 4.2 Subshell Creation Flow

1. Check for existing Stand environment (prevent nesting)
2. Detect user's shell type
3. Prepare environment variables
4. Configure shell-specific prompt
5. Spawn shell process with inherited stdio
6. Wait for shell to exit
7. Clean up state if necessary

### 4.3 Command Execution Flow

1. Parse command and arguments
2. Load specified environment
3. Create child process
4. Inject environment variables
5. Execute command
6. Capture and return exit code

## 5. File System Layout

### 5.1 Project Structure

```
<project-root>/
├── .stand.toml            # Single TOML file containing all configuration and variables
└── .gitignore            # Auto-updated with .stand.toml file
```

### 5.2 TOML Configuration Format

The `.stand.toml` file uses TOML format and contains:

```toml
version = "2.0"

[settings]
show_env_in_prompt = true
nested_shell_behavior = "prevent"

# Common variables shared across all environments
[common]
APP_NAME = "MyApplication"
LOG_FORMAT = "json"
TIMEZONE = "UTC"

# Development environment
[environments.dev]
description = "Development environment"
color = "green"
requires_confirmation = false
DATABASE_URL = "postgres://localhost:5432/dev"
API_KEY = "dev-key-123"
DEBUG = "true"

# Production environment (inherits from dev)
[environments.prod]
description = "Production environment"
color = "red"
extends = "dev"
requires_confirmation = true
DATABASE_URL = "postgres://prod.example.com/myapp"
API_KEY = "${PROD_API_KEY}"  # Environment variable expansion
DEBUG = "false"
```

### 5.3 Configuration Discovery and Migration

**Discovery Precedence:**
Stand discovers configuration in the following order:
1. `.stand.toml` (preferred TOML format)
2. `.stand/config.yaml` (legacy format, deprecated)

**Migration from YAML to TOML:**
To migrate from legacy YAML configuration:

Legacy multi-file structure:
```
.stand/
├── config.yaml          # Environment definitions
├── common.env           # Shared variables  
├── dev.env              # Development variables
└── prod.env             # Production variables
```

New single-file structure:
```toml
version = "2.0"

# Variables shared across all environments
[common]
APP_NAME = "MyApplication"
LOG_FORMAT = "json"

[environments.dev]
description = "Development environment"
DATABASE_URL = "postgres://localhost:5432/dev"
API_KEY = "dev-key-123"

[environments.prod]
description = "Production environment"
extends = "dev"  # Inherit from dev environment
DATABASE_URL = "postgres://prod.example.com/app"
API_KEY = "${PROD_API_KEY}"
```

**Variable Interpolation Rules:**
- Single-pass expansion: `${VAR}` syntax only
- Error on unterminated placeholders: `${VAR` (missing closing brace)
- Error on empty variable names: `${}`
- No nested expansion: `${VAR_${SUFFIX}}` is not supported

**Deprecation Timeline:**
- Legacy YAML support will be removed in v3.0
- Deprecation warnings will be shown when YAML config is detected
- Migration command: `stand migrate` (future feature)

### 5.4 User Configuration

```
~/.config/stand/           # Future: Global configuration
└── config.toml           # Future: User preferences
```

## 6. Command Processing

### 6.1 Command Routing

```
CLI Input → Parser → Command Enum → Handler Function → Result
```

Commands map to distinct handlers:
- `init` → Initialize configuration
- `shell` → Create subshell
- `exec` → Execute command
- `list` → Display environments
- `show` → Display variables
- `set/unset` → Modify variables
- `validate` → Check configuration
- `current` → Show active environment

### 6.2 Error Handling Strategy

All errors bubble up through Result types with context:
1. Parse errors → Show usage help
2. Configuration errors → Show validation details
3. Environment errors → List available options
4. System errors → Provide troubleshooting steps

## 7. Shell Integration

### 7.1 Shell Detection

1. Read `$SHELL` environment variable
2. Extract shell name from path
3. Map to known shell type
4. Fall back to generic POSIX behavior

### 7.2 Prompt Customization

Each shell requires different prompt syntax:
- **Bash**: Uses `PS1` with escape sequences
- **Zsh**: Uses `PROMPT` with percent codes
- **Fish**: Uses `fish_prompt` function

### 7.3 Environment Isolation

Subshells provide complete isolation:
- Parent environment unchanged
- No variable leakage
- Clean exit restores original state
- Process tree independence

## 8. Security Design

### 8.1 File Permissions

- Check and warn for world-readable sensitive files
- Enforce 0600 permissions on state files
- Validate ownership of configuration files

### 8.2 Variable Handling

- Never log sensitive values
- Sanitize error messages
- No variables in command history
- Clear memory after use

### 8.3 Git Integration

Automatically maintain `.gitignore`:
- Add `.stand.toml` file (if contains sensitive variables)
- Preserve existing entries
- Support for per-environment .gitignore patterns

## 9. Performance Considerations

### 9.1 Optimization Strategies

- **Lazy Loading**: Parse configuration only when needed
- **Caching**: Keep parsed TOML in memory during session
- **Minimal Allocations**: Reuse buffers where possible
- **Fast TOML Parsing**: Single file parsing is more efficient than multiple files

### 9.2 Binary Size Optimization

- Link-time optimization (LTO)
- Strip symbols in release builds
- Optimize for size (`opt-level = "z"`)
- Single codegen unit

## 10. Testing Strategy

### 10.1 Test Layers

1. **Unit Tests**: Individual functions and modules
2. **Integration Tests**: Component interactions
3. **End-to-End Tests**: Full command workflows
4. **Shell Tests**: Shell-specific behavior

### 10.2 Test Coverage Areas

- TOML configuration parsing and validation
- Variable resolution precedence (common → parent → environment → session)
- Environment inheritance through `extends` field
- Shell detection and prompt formatting
- Subshell creation and cleanup
- Command execution and exit codes
- Error handling and recovery

## 11. Platform Support

### 11.1 Operating Systems

- Linux (glibc 2.17+)
- macOS (10.13+)
- WSL2 (Windows Subsystem for Linux)

### 11.2 Architectures

- x86_64
- aarch64 (ARM64)

### 11.3 Shell Compatibility

Shells with version requirements:
- Bash 4.0+
- Zsh 5.0+
- Fish 3.0+

## 12. Distribution

### 12.1 Release Artifacts

- Static binaries per platform/architecture
- Compressed archives (.tar.gz, .zip)
- Checksums file (SHA256)
- Installation script

### 12.2 Installation Methods

1. **Direct Download**: GitHub releases
2. **Package Managers**: Cargo, Homebrew
3. **From Source**: `cargo install`

## 13. Monitoring and Diagnostics

### 13.1 Debug Mode

Environment variable `STAND_DEBUG=1` enables:
- Verbose logging
- Configuration dump
- Variable resolution trace
- Shell detection details

### 13.2 Health Checks

- Configuration validation
- State file integrity
- Shell compatibility
- File permissions

## 14. Upgrade Path

### 14.1 Version Migration

- Configuration version field for compatibility
- Automatic migration for minor versions
- Manual migration guide for major versions

### 14.2 Backward Compatibility

- Support previous configuration format for one major version
- Clear deprecation warnings
- Migration commands available

## 15. Extension Points

### 15.1 Future Extensibility

Designed to support future additions:
- Custom variable sources (vault, cloud)
- Hook system (pre/post switch)
- Plugin architecture
- Additional shell support
- Template engine for variables

### 15.2 Configuration Extensions

Reserved configuration namespaces:
- `plugins:` for future plugin system
- `hooks:` for lifecycle hooks
- `templates:` for variable templating
- `sources:` for external variable sources