AgentSkillsCN

config-transparency-centralized

倡导一种集中化、透明化的 .env 文件配置理念,杜绝隐藏变量、静默回退或默认值。适用于处理配置、配置文件、环境变量、后台变量、回退机制,或探讨开发哲学时使用。所有配置都必须在 .env 中明确声明,以 .env.example 作为真实参考。

SKILL.md
--- frontmatter
name: config-transparency-centralized
description: Configuration philosophy requiring centralized, transparent .env files with no hidden variables, silent fallbacks, or defaults. Use when dealing with config, configuration, env variables, background variables, fallbacks, or dev philosophy. All configuration must be explicit in .env with .env.example as ground truth.
<!-- [Created by Claude: 67f7b402-050c-4754-bdad-8c5e777eddd2] -->

Configuration Transparency & Centralization

Strict configuration philosophy requiring explicit, centralized configuration with zero tolerance for hidden variables or silent fallbacks.

Quick Reference

Core Principle: .env.example is the ground truth. If it's not there, it doesn't exist.

bash
# ✅ CORRECT - Explicit, fails loudly if missing
SHIM_HOST=${SHIM_HOST:?Error: SHIM_HOST not set in .env}

# ❌ WRONG - Silent fallback hides configuration requirement
SHIM_HOST=${SHIM_HOST:-127.0.0.1}

Five Pillars of Configuration Transparency

1. Centralization

ALL configuration must live in .env

✅ Allowed❌ Forbidden
Reading from .envHardcoded paths in code
Environment variablesFallback defaults in code
.env overridesHidden configuration
Explicit env vars"Helpful" defaults

Example:

python
# ❌ WRONG - Hardcoded fallback
cli_path = os.environ.get("CLAUDE_CODE_CLI", "~/swe/claude-code-2.1.12/cli.js")

# ✅ CORRECT - Fail if not set
cli_path = os.environ["CLAUDE_CODE_CLI"]  # Raises KeyError if missing

2. Maximum Transparency

Every configurable parameter must be visible in .env

Rules:

  • If a variable can be configured, it MUST be in .env
  • No hidden variables discoverable only by reading code
  • No "advanced" options hidden behind environment variables not documented in .env
  • All paths, ports, hosts, timeouts, flags must be explicit

Anti-Pattern Example:

python
# ❌ WRONG - Hidden configuration option
debug_mode = os.environ.get("SECRET_DEBUG_MODE", "false")

Correct Pattern:

bash
# ✅ CORRECT - In .env
DEBUG_MODE=false
SECRET_DEBUG_MODE=false  # If needed, make it explicit

3. Fail Loudly

Missing required configuration = Immediate failure with clear error

Rules:

  • Server refuses to start if required config missing
  • Error message must specify EXACTLY which variable is missing
  • Error message must specify WHERE to add it (.env file)
  • No graceful degradation
  • No silent fallbacks
  • No "best effort" behavior

Implementation Pattern (Python):

python
import os
import sys

def get_required_env(key: str, description: str = "") -> str:
    """Get required environment variable or fail loudly."""
    value = os.environ.get(key)
    if value is None:
        desc = f" ({description})" if description else ""
        print(f"ERROR: Required environment variable '{key}' not set{desc}", file=sys.stderr)
        print(f"Add '{key}=<value>' to your .env file", file=sys.stderr)
        print(f"See .env.example for all required variables", file=sys.stderr)
        sys.exit(1)
    return value

# Usage
SHIM_HOST = get_required_env("SHIM_HOST", "host to bind server")
SHIM_PORT = get_required_env("SHIM_PORT", "port to bind server")
CLAUDE_CODE_CLI = get_required_env("CLAUDE_CODE_CLI", "path to Claude CLI")

Implementation Pattern (Bash):

bash
#!/bin/bash
set -euo pipefail

# Fail loudly if variable not set
: "${SHIM_HOST:?ERROR: SHIM_HOST not set in .env}"
: "${SHIM_PORT:?ERROR: SHIM_PORT not set in .env}"
: "${CLAUDE_CODE_CLI:?ERROR: CLAUDE_CODE_CLI not set in .env}"

4. .env.example as Ground Truth

.env.example is the contract and documentation

Rules:

  • .env.example MUST exist in every project root
  • .env.example MUST be kept in sync with .env
  • .env.example documents ALL required variables
  • .env.example documents ALL optional variables
  • Sensitive values replaced with stubs/placeholders
  • Comments explain what each variable does

.env.example Format:

bash
# =============================================================================
# Server Configuration (REQUIRED)
# =============================================================================

# Host to bind server (127.0.0.1=localhost, 192.168.1.x=LAN, 0.0.0.0=all)
SHIM_HOST=127.0.0.1

# Port for shim server
SHIM_PORT=8787

# =============================================================================
# CLI Configuration (REQUIRED)
# =============================================================================

# Path to Claude Code CLI (use ~/symlinks/claude for latest)
CLAUDE_CODE_CLI=~/symlinks/claude

# Path to Codex CLI (use ~/symlinks/codex for latest)
CODEX_CLI=~/symlinks/codex

# =============================================================================
# Runtime Configuration (REQUIRED)
# =============================================================================

# Working directory for spawned CLI agents
SHIM_DEFAULT_CWD=~/agent-home

# =============================================================================
# Authentication (REQUIRED - DO NOT COMMIT REAL VALUES)
# =============================================================================

# OAuth token for Claude (keep this secret!)
CLAUDE_OAUTH_TOKEN=<your-oauth-token-here>

# =============================================================================
# Optional Configuration
# =============================================================================

# Log directory (optional, defaults to ~/centralized-logs/shim)
# SHIM_LOG_DIR=~/centralized-logs/shim

Version Control:

bash
# .gitignore
.env          # Never commit (contains secrets)
.env.local    # Never commit (local overrides)

# Always commit .env.example (no secrets)

5. No Silent Behavior

.env.example defines the contract - no hidden surprises

Forbidden Patterns:

Silent Fallbacks:

python
port = os.environ.get("PORT", 8080)  # WRONG - hides requirement

Auto-Detection:

python
if os.path.exists("/usr/local/bin/claude"):
    cli = "/usr/local/bin/claude"  # WRONG - hidden logic

Smart Defaults:

python
if platform.system() == "Darwin":
    cli = "~/Library/Application Support/claude"  # WRONG - platform-specific hidden logic

Graceful Degradation:

python
try:
    cli = os.environ["CLAUDE_CLI"]
except KeyError:
    cli = find_in_path("claude")  # WRONG - silent fallback

Correct Pattern:

Explicit and Loud:

python
# Read required variables (fail if missing)
SHIM_HOST = os.environ["SHIM_HOST"]
SHIM_PORT = int(os.environ["SHIM_PORT"])
CLAUDE_CODE_CLI = os.environ["CLAUDE_CODE_CLI"]

# Validate paths exist
if not os.path.exists(os.path.expanduser(CLAUDE_CODE_CLI)):
    print(f"ERROR: CLAUDE_CODE_CLI path does not exist: {CLAUDE_CODE_CLI}")
    sys.exit(1)

Validation Checklist

Use this checklist when reviewing configuration code:

Code Review Checklist

  • No hardcoded paths, ports, or configuration values in code
  • All os.environ.get() with defaults changed to os.environ[] (fail if missing)
  • No fallback logic (if/else chains, try/except for missing config)
  • No platform-specific defaults (Darwin vs Linux paths)
  • No auto-detection logic (searching PATH, checking file existence)
  • Startup validation fails loudly if config missing
  • Error messages specify which variable is missing
  • Error messages point to .env and .env.example

.env.example Review Checklist

  • .env.example exists in project root
  • All variables in code are documented in .env.example
  • Each variable has a comment explaining its purpose
  • Sensitive values replaced with placeholders
  • Required vs optional variables clearly marked
  • Example values are realistic and helpful
  • File is organized into logical sections with headers
  • .env.example is committed to version control
  • .env is in .gitignore

Common Violations & Fixes

Violation 1: Hardcoded Fallback

❌ Before:

python
cli_path = os.environ.get(
    "CLAUDE_CODE_CLI",
    os.path.expanduser("~/swe/claude-code-2.1.12/cli.js")
)

✅ After:

python
try:
    cli_path = os.environ["CLAUDE_CODE_CLI"]
except KeyError:
    print("ERROR: CLAUDE_CODE_CLI not set in .env", file=sys.stderr)
    print("Add: CLAUDE_CODE_CLI=~/symlinks/claude", file=sys.stderr)
    print("See .env.example for details", file=sys.stderr)
    sys.exit(1)

.env.example:

bash
# Path to Claude Code CLI (use ~/symlinks/claude for latest)
CLAUDE_CODE_CLI=~/symlinks/claude

Violation 2: Default Port/Host

❌ Before:

python
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8787)

✅ After:

python
# .env must provide these
host_from_env = os.environ["SHIM_HOST"]
port_from_env = int(os.environ["SHIM_PORT"])

parser.add_argument("--host", default=host_from_env)
parser.add_argument("--port", type=int, default=port_from_env)

.env.example:

bash
# Host to bind server (127.0.0.1=localhost, 192.168.1.x=LAN)
SHIM_HOST=127.0.0.1

# Port for shim server
SHIM_PORT=8787

Violation 3: Silent CWD Fallback

❌ Before:

python
default_cwd = os.environ.get("SHIM_DEFAULT_CWD", os.getcwd())

✅ After:

python
try:
    default_cwd = os.path.expanduser(os.environ["SHIM_DEFAULT_CWD"])
except KeyError:
    print("ERROR: SHIM_DEFAULT_CWD not set in .env", file=sys.stderr)
    print("This specifies the working directory for CLI agents", file=sys.stderr)
    print("Add: SHIM_DEFAULT_CWD=~/agent-home", file=sys.stderr)
    sys.exit(1)

if not os.path.exists(default_cwd):
    print(f"ERROR: SHIM_DEFAULT_CWD directory does not exist: {default_cwd}", file=sys.stderr)
    print(f"Create it with: mkdir -p {default_cwd}", file=sys.stderr)
    sys.exit(1)

.env.example:

bash
# Working directory for spawned CLI agents (must exist)
SHIM_DEFAULT_CWD=~/agent-home

Violation 4: Missing .env.example

❌ Before:

  • No .env.example file
  • Configuration discovered only by reading code
  • New users must guess what variables are needed

✅ After:

Create comprehensive .env.example:

bash
# =============================================================================
# VSCode Shim Configuration
# =============================================================================
# Copy this file to .env and customize values
# DO NOT commit .env (contains secrets)
# DO commit .env.example (template only)

# =============================================================================
# Server Configuration (REQUIRED)
# =============================================================================

# Host to bind server
# 127.0.0.1 = localhost only (secure, requires SSH tunnel)
# 192.168.1.x = LAN interface (for local network access)
# 0.0.0.0 = all interfaces (DANGEROUS - exposes to all networks)
SHIM_HOST=127.0.0.1

# Port for Claude shim server
SHIM_PORT=8787

# Port for Codex shim server
CODEX_SHIM_PORT=9288

# =============================================================================
# CLI Paths (REQUIRED)
# =============================================================================

# Path to Claude Code CLI (use symlink for version management)
CLAUDE_CODE_CLI=~/symlinks/claude

# Path to Codex CLI (use symlink for version management)
CODEX_CLI=~/symlinks/codex

# =============================================================================
# Runtime Configuration (REQUIRED)
# =============================================================================

# Working directory for spawned CLI agents
# Directory must exist before starting server
SHIM_DEFAULT_CWD=~/agent-home

# =============================================================================
# Logging (OPTIONAL)
# =============================================================================

# Directory for centralized logs
# Uncomment to override default
# CLAUDE_VSCODE_SHIM_LOG_DIR=~/centralized-logs/claude-shim
# CODEX_SHIM_LOG_DIR=~/centralized-logs/codex-shim

# =============================================================================
# Development (OPTIONAL)
# =============================================================================

# Enable debug mode (verbose logging)
# DEBUG=false

Implementation Guide

Step 1: Audit Existing Code

bash
# Find all environment variable accesses with defaults
grep -r "os.environ.get" . --include="*.py"
grep -r "getenv" . --include="*.py"
grep -r '${.*:-' . --include="*.sh"

# Find hardcoded paths
grep -r "~/swe/" . --include="*.py"
grep -r "/Users/" . --include="*.py"
grep -r "127.0.0.1" . --include="*.py"
grep -r "8787\|9288" . --include="*.py"

Step 2: Create .env.example

Document every variable discovered in Step 1.

Step 3: Remove All Defaults

Replace os.environ.get(key, default) with:

  1. os.environ[key] (raises KeyError)
  2. Wrap in try/except with helpful error message
  3. Reference .env.example in error

Step 4: Add Startup Validation

python
def validate_config():
    """Validate all required config exists and is valid."""
    required_vars = [
        "SHIM_HOST",
        "SHIM_PORT",
        "CLAUDE_CODE_CLI",
        "CODEX_CLI",
        "SHIM_DEFAULT_CWD",
    ]

    missing = []
    for var in required_vars:
        if var not in os.environ:
            missing.append(var)

    if missing:
        print("ERROR: Missing required environment variables:", file=sys.stderr)
        for var in missing:
            print(f"  - {var}", file=sys.stderr)
        print("\nAdd these to your .env file", file=sys.stderr)
        print("See .env.example for all required variables", file=sys.stderr)
        sys.exit(1)

    # Validate paths exist
    for var in ["CLAUDE_CODE_CLI", "CODEX_CLI", "SHIM_DEFAULT_CWD"]:
        path = os.path.expanduser(os.environ[var])
        if not os.path.exists(path):
            print(f"ERROR: {var} path does not exist: {path}", file=sys.stderr)
            sys.exit(1)

# Call at startup
if __name__ == "__main__":
    validate_config()
    # ... rest of startup

Step 5: Update Documentation

Add to README.md:

markdown
## Configuration

All configuration is managed through the `.env` file.

1. Copy `.env.example` to `.env`:
   ```bash
   cp .env.example .env
  1. Edit .env and set all required variables

  2. Start the server:

    bash
    ./launchers/launch_server.sh
    

If any required variables are missing, the server will fail to start with a clear error message.

code

---

## Benefits

### For Developers

1. **Single Source of Truth**: All config in one place (`.env`)
2. **No Surprises**: No hidden variables or fallbacks
3. **Clear Errors**: Know exactly what's missing when things fail
4. **Easy Onboarding**: `.env.example` shows everything needed

### For Agents

1. **Discoverable**: Can read `.env.example` to know all configuration
2. **Predictable**: No hidden behavior based on platform or environment
3. **Debuggable**: Configuration errors are loud and specific
4. **Automatable**: Can generate `.env` from `.env.example` template

### For Operations

1. **Consistent**: Same configuration pattern across all projects
2. **Auditable**: Configuration is explicit and version-controlled (via `.env.example`)
3. **Secure**: Secrets stay in `.env` (never committed)
4. **Portable**: Copy `.env` to deploy anywhere

---

## Anti-Patterns to Avoid

### ❌ The "Smart Default" Anti-Pattern

```python
# WRONG - Tries to be "helpful"
if os.path.exists("/usr/local/bin/claude"):
    cli = "/usr/local/bin/claude"
elif os.path.exists(os.path.expanduser("~/swe/claude-code-2.1.15/cli.js")):
    cli = os.path.expanduser("~/swe/claude-code-2.1.15/cli.js")
else:
    cli = os.environ.get("CLAUDE_CODE_CLI", "claude")

Why wrong: Hidden logic, platform-specific, hard to debug, fails silently

Correct:

python
cli = os.environ["CLAUDE_CODE_CLI"]

❌ The "Graceful Degradation" Anti-Pattern

python
# WRONG - Fails silently
try:
    port = int(os.environ["SHIM_PORT"])
except (KeyError, ValueError):
    port = 8787  # Use default

Why wrong: Silently ignores configuration errors, hides problems

Correct:

python
try:
    port = int(os.environ["SHIM_PORT"])
except KeyError:
    print("ERROR: SHIM_PORT not set in .env", file=sys.stderr)
    sys.exit(1)
except ValueError:
    print(f"ERROR: SHIM_PORT must be a number, got: {os.environ['SHIM_PORT']}", file=sys.stderr)
    sys.exit(1)

❌ The "Optional Config" Anti-Pattern

python
# WRONG - Hidden optional feature
if os.environ.get("ENABLE_FEATURE_X") == "true":
    setup_feature_x()

Why wrong: Feature is hidden unless you read the code

Correct (.env.example):

bash
# Enable experimental feature X (optional)
# Uncomment to enable
# ENABLE_FEATURE_X=true

Enforcement

Pre-commit Hook

bash
#!/bin/bash
# .git/hooks/pre-commit

# Check .env.example exists
if [ ! -f .env.example ]; then
    echo "ERROR: .env.example is missing"
    echo "Create .env.example documenting all required variables"
    exit 1
fi

# Check for hardcoded defaults in Python
if git diff --cached --name-only | grep "\.py$" | xargs grep -l "os.environ.get.*,"; then
    echo "ERROR: Found os.environ.get() with default values"
    echo "Use os.environ[] instead to fail loudly if missing"
    exit 1
fi

# Check .env is not committed
if git diff --cached --name-only | grep "^\.env$"; then
    echo "ERROR: .env should not be committed (contains secrets)"
    echo "Only commit .env.example"
    exit 1
fi

CI/CD Check

yaml
# .github/workflows/config-validation.yml
name: Config Validation
on: [pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Check .env.example exists
        run: |
          if [ ! -f .env.example ]; then
            echo "::error::.env.example is missing"
            exit 1
          fi

      - name: Check for hardcoded defaults
        run: |
          if grep -r "os.environ.get.*," . --include="*.py"; then
            echo "::error::Found os.environ.get() with defaults - use os.environ[] instead"
            exit 1
          fi

FAQ

Q: What about truly optional configuration?

A: Still document it in .env.example with a comment:

bash
# Optional: Enable debug logging (uncomment to enable)
# DEBUG=true

Q: What if I need different config for dev vs prod?

A: Use separate .env files:

bash
.env              # Local development (gitignored)
.env.example      # Template (committed)
.env.production   # Production secrets (never committed, deployed separately)

Load the appropriate file at runtime.

Q: What about command-line arguments?

A: CLI args can OVERRIDE .env, but .env must still provide defaults:

python
# .env provides the default
default_host = os.environ["SHIM_HOST"]

# CLI can override
parser.add_argument("--host", default=default_host)

Q: What if the user forgot to create .env?

A: Fail immediately with helpful error:

python
if not os.path.exists(".env"):
    print("ERROR: .env file not found", file=sys.stderr)
    print("Copy .env.example to .env and customize:", file=sys.stderr)
    print("  cp .env.example .env", file=sys.stderr)
    sys.exit(1)

Summary

Configuration Transparency & Centralization is a strict philosophy requiring:

  1. ✅ All configuration in .env
  2. .env.example as ground truth
  3. ✅ No hidden variables or fallbacks
  4. ✅ Fail loudly if config missing
  5. ✅ Maximum transparency

Remember: If it's not in .env.example, it doesn't exist. If it's required but missing, fail immediately with a clear error message.


References

  • Twelve-Factor App: Config
  • Environment Variables Best Practices
  • Security: Never commit secrets (.env in .gitignore)
  • Principle of Least Surprise: No hidden behavior