# Global Env Config Agent

> **Greek:** Periballon (Periballon) -- "environment/surroundings"
> **Sanskrit:** Parivesa (Parivesa) -- "environment/context"
> **Tagline:** *"Same code, different worlds"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `global_env_config` |
| Name | Global Env Config Agent |
| Phase | 7 -- Global Architecture |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Produce a comprehensive environment configuration schema that defines every environment variable needed across all environments (development, staging, production, test), with type validation, sensitivity flags, defaults for development, and a .env.example template that never contains real secrets.

| Priority | Objective |
|---|---|
| primary | Extract all environment variables needed by all integrations, security policies, and module configurations into a unified schema with per-environment definitions |
| secondary | Generate a .env.example template with safe default values for development and clear placeholder comments for production secrets |
| tertiary | Define config validation rules that can be used at application startup to verify all required env vars are present and correctly typed |

---

## Inputs

### global_integrations.json
- **Source:** `global_integrations` -> `agent_output/architecture/global/global_integrations.json`
- **Required:** yes
- **Shape:**
```json
{
  "integrations": [
    {
      "integration_id": "string",
      "name": "string",
      "env_vars_needed": [
        {
          "key": "string -- env var name",
          "description": "string",
          "sensitive": "boolean",
          "required_in": ["string -- environments"],
          "example_value": "string | null"
        }
      ]
    }
  ],
  "total_env_vars_needed": "number"
}
```

### global_security_policies.json
- **Source:** `global_security` -> `agent_output/architecture/global/global_security_policies.json`
- **Required:** yes
- **Shape:**
```json
{
  "auth_strategy": {
    "type": "string",
    "config": {
      "token_expiry": "string",
      "refresh_token_expiry": "string",
      "algorithm": "string"
    }
  },
  "cors_policy": {
    "allowed_origins": ["string"]
  },
  "rate_limiting": {
    "global": {
      "window_ms": "number",
      "max_requests": "number"
    }
  },
  "encryption_at_rest": {
    "enabled": "boolean",
    "algorithm": "string"
  }
}
```

### All modules' contracts (summary)
- **Source:** Various Phase 5 agents -> per-module contract outputs
- **Required:** yes (scanned for database URLs, port configs, etc.)
- **Shape:**
```json
{
  "module_id": "string",
  "database_config": {
    "provider": "string -- e.g., 'postgresql'",
    "url_env_var": "string -- e.g., 'DATABASE_URL'"
  }
}
```

---

## Outputs

### environment_config_schema.json
- **Path:** `agent_output/architecture/global/environment_config_schema.json`
- **Format:** `json`
- **Consumers:** `architect_reconcile`, `impl_prep`, `be_impl`
- **Shape:**
```json
{
  "generated_at": "string -- ISO-8601 timestamp",
  "total_variables": "number -- total unique env vars across all environments",
  "total_sensitive": "number -- count of sensitive variables",
  "environments": [
    {
      "name": "string -- 'development' | 'staging' | 'production' | 'test'",
      "description": "string -- purpose of this environment",
      "variables": [
        {
          "key": "string -- environment variable name (e.g., 'DATABASE_URL')",
          "type": "string -- 'string' | 'number' | 'boolean' | 'url' | 'email' | 'port' | 'json'",
          "required": "boolean -- whether this var must be set in this environment",
          "default": "string | null -- default value (only for development/test, never for production secrets)",
          "sensitive": "boolean -- whether this is a secret/credential",
          "description": "string -- what this variable configures",
          "source_integration": "string | null -- integration_id that requires this var (null if core app config)",
          "category": "string -- 'database' | 'auth' | 'integration' | 'server' | 'feature_flag' | 'logging' | 'cache' | 'email' | 'storage' | 'monitoring'",
          "validation": {
            "format": "string | null -- regex pattern or format name (e.g., 'url', 'email')",
            "min_length": "number | null",
            "max_length": "number | null",
            "allowed_values": ["string | null -- enum of allowed values"],
            "example": "string -- example value for documentation"
          }
        }
      ]
    }
  ],
  "env_example": {
    "description": "string -- '.env.example file content for developer onboarding'",
    "sections": [
      {
        "section_name": "string -- e.g., 'Database', 'Authentication', 'Integrations'",
        "comment": "string -- section header comment",
        "variables": [
          {
            "key": "string -- env var name",
            "value": "string -- safe default or placeholder (e.g., 'your-stripe-secret-key-here')",
            "comment": "string -- inline comment explaining the variable"
          }
        ]
      }
    ]
  },
  "config_validation_rules": [
    {
      "rule_id": "string -- unique rule identifier (e.g., 'CVR-001')",
      "type": "string -- 'required_check' | 'type_check' | 'format_check' | 'dependency_check' | 'mutual_exclusion'",
      "description": "string -- what this rule validates",
      "variables_involved": ["string -- env var keys this rule applies to"],
      "condition": "string -- validation condition (e.g., 'must be set when NODE_ENV=production')",
      "error_message": "string -- error message when validation fails",
      "severity": "string -- 'fatal' | 'warning'"
    }
  ],
  "startup_validation_script": {
    "description": "string -- description of what the startup validation does",
    "checks": [
      {
        "check_name": "string -- e.g., 'required_vars_present'",
        "description": "string -- what this check verifies",
        "fails_on": "string -- condition that causes failure"
      }
    ]
  },
  "variable_groups": {
    "core": ["string -- core app config vars (PORT, NODE_ENV, etc.)"],
    "database": ["string -- database config vars"],
    "auth": ["string -- authentication config vars"],
    "integrations": {
      "integration_name": ["string -- vars for this integration"]
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `global_integrations` | `global_integrations.json` | Provides all integration-required env vars |
| input | `global_security` | `global_security_policies.json` | Provides security-related config (JWT secret, token expiry, CORS origins) |
| input | Various Phase 5 agents (all modules) | Module contracts | Provides database URLs, port configs, and other module-specific config |
| barrier | ALL Phase 6 agents | All modules must complete Phase 6 before this global agent starts |

| Blocks | Agent | Why |
|---|---|---|
| output | `architect_reconcile` | Reconcile needs env config for complete architecture |
| output | `impl_prep` | Impl prep agent generates .env.example from this output |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `global_env_config`. Use this ID in all `node_write`, `node_read`, `tracker_read`, and `tracker_update` calls.

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | (none) | Global agent -- does not read `md.a` |
| write | `ag` | Report agent status (completed/failed) |

### Output Meta

This agent does not produce routing/coordination metadata. `output_meta: null`.

### Completion Signal

- **On success:** `tracker_update(agent_id: "global_env_config", status: "completed")`
- **On failure:** `tracker_update(agent_id: "global_env_config", status: "failed", add_intervention: { id: "...", agent_id: "global_env_config", type: "error", message: "..." })`

### Scope Resolution

Global agent -- does NOT read `md.a`. Reads all modules' per-module artifacts in a single pass.

```
1. node_read(agent_id: "global_env_config", input_key: "global_integrations")
2. node_read(agent_id: "global_env_config", input_key: "global_security_policies")
3. node_read(agent_id: "global_env_config", input_key: "module_contracts_all")
4. Process all inputs → build environment config schema
5. node_write(agent_id: "global_env_config", output_key: "environment_config_schema", data: {...})
6. tracker_update(agent_id: "global_env_config", status: "completed")
```

---

## Compressed Keymap

Use these compressed keys in all `node_write` calls. The registry validates against this map — unknown keys are rejected.

### Output: `environment_config_schema.json`

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | ISO-8601 timestamp |
| `tv` | total_variables | Total unique env vars across all environments |
| `ts` | total_sensitive | Count of sensitive variables |
| `en` | environments | Array of per-environment definitions |
| `en.nm` | name | development / staging / production / test |
| `en.ds` | description | Purpose of this environment |
| `en.vr` | variables | Array of variable definitions |
| `en.vr.ky` | key | Environment variable name (e.g., 'DATABASE_URL') |
| `en.vr.tp` | type | string / number / boolean / url / email / port / json |
| `en.vr.rq` | required | Whether this var must be set |
| `en.vr.df` | default | Default value (only for dev/test, never production secrets) |
| `en.vr.sn` | sensitive | Whether this is a secret/credential |
| `en.vr.ds` | description | What this variable configures |
| `en.vr.si` | source_integration | Integration ID requiring this var (null if core) |
| `en.vr.ct` | category | database / auth / integration / server / feature_flag / logging / cache / email / storage / monitoring |
| `en.vr.vl` | validation | Validation rules |
| `en.vr.vl.fm` | format | Regex pattern or format name |
| `en.vr.vl.mn` | min_length | Minimum length |
| `en.vr.vl.mx` | max_length | Maximum length |
| `en.vr.vl.av` | allowed_values | Enum of allowed values |
| `en.vr.vl.ex` | example | Example value for documentation |
| `ee` | env_example | .env.example template definition |
| `ee.ds` | description | Template file description |
| `ee.sc` | sections | Template sections |
| `ee.sc.sn` | section_name | Section name (e.g., 'Database') |
| `ee.sc.cm` | comment | Section header comment |
| `ee.sc.vr` | variables | Variables in this section |
| `ee.sc.vr.ky` | key | Env var name |
| `ee.sc.vr.vl` | value | Safe default or placeholder |
| `ee.sc.vr.cm` | comment | Inline comment |
| `cv` | config_validation_rules | Startup config validation rules |
| `cv.ri` | rule_id | Unique rule ID (e.g., 'CVR-001') |
| `cv.tp` | type | required_check / type_check / format_check / dependency_check / mutual_exclusion |
| `cv.ds` | description | What this rule validates |
| `cv.vi` | variables_involved | Env var keys this rule applies to |
| `cv.cn` | condition | Validation condition |
| `cv.em` | error_message | Error message when validation fails |
| `cv.sv` | severity | fatal / warning |
| `sv` | startup_validation_script | Startup validation script definition |
| `sv.ds` | description | What the startup validation does |
| `sv.ck` | checks | Array of checks |
| `sv.ck.cn` | check_name | Check name (e.g., 'required_vars_present') |
| `sv.ck.ds` | description | What this check verifies |
| `sv.ck.fo` | fails_on | Condition that causes failure |
| `vg` | variable_groups | Variables grouped by category |
| `vg.cr` | core | Core app config vars |
| `vg.db` | database | Database config vars |
| `vg.au` | auth | Authentication config vars |
| `vg.ig` | integrations | Integration-specific vars (keyed by name) |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write environment_config_schema output via registry-validated compressed keys. Agent calls `node_write(agent_id: "global_env_config", output_key: "environment_config_schema", data: {...})`. | Pending |
| `node_read` | Read upstream artifacts (global_integrations, global_security_policies, module_contracts_all). Agent calls `node_read(agent_id: "global_env_config", input_key: "global_integrations")`. | Pending |
| `tracker_read` | Read pipeline state. Agent calls `tracker_read(agent_id: "global_env_config", fields: [...])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "global_env_config", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must list ALL env vars needed by all integrations from global_integrations.json |
| R-002 | `constraint` | `must` | Must flag all sensitive vars with sensitive=true |
| R-003 | `constraint` | `must` | Must provide safe defaults for development environment (localhost URLs, test keys, etc.) |
| R-004 | `not_allowed` | `must` | Must NOT include actual secret values, real API keys, or production credentials |
| R-005 | `constraint` | `must` | Must include security-related env vars from global_security_policies.json (JWT_SECRET, TOKEN_EXPIRY, etc.) |
| R-006 | `constraint` | `must` | Must include core application vars (NODE_ENV, PORT, DATABASE_URL) |
| R-007 | `output_quality` | `must` | Every variable must have a type, description, and validation example |
| R-008 | `output_quality` | `should` | Config validation rules should cover type checks, required checks, and format checks |
| R-009 | `scope_boundary` | `should` | Variables should be grouped by category (database, auth, integration, server, etc.) |
| R-010 | `output_quality` | `should` | The .env.example should have clear section headers and comments explaining each variable |
| R-011 | `data_handling` | `must` | Production environment must not have defaults for sensitive variables |
| R-012 | `constraint` | `should` | Dependency checks should validate that related env vars are set together (e.g., SMTP_HOST requires SMTP_PORT) |
| R-013 | `constraint` | `must` | Must use compressed keys as defined in the Compressed Keymap section for all `node_write` / `node_read` calls. Never use expanded/full key names. |
| R-014 | `constraint` | `must` | Must use `node_write` to write output and `node_read` to read upstream artifacts. Must not use raw file writes, generic file_writer, or any other method. |
| R-015 | `constraint` | `must` | Must call `tracker_update(agent_id: "global_env_config", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "global_env_config", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32000 |
| max_env_vars | 200 |

---

## Scope Boundary

**In scope:**
- Extracting all env vars from integrations, security, and module configs
- Defining per-environment variable schemas (development, staging, production, test)
- Generating .env.example template with safe defaults
- Defining config validation rules for startup verification
- Categorizing variables by purpose (database, auth, integration, etc.)
- Flagging sensitive variables
- Defining validation formats and constraints per variable

**Out of scope:**
- Setting actual env var values for production
- Creating or managing secrets in secret managers (Vault, AWS Secrets Manager)
- Implementing config loading code (Phase 10)
- Modifying integrations or security policies (read-only)
- Infrastructure provisioning (servers, databases, CDN)
- CI/CD environment configuration

---

## Triggers

- Orchestrator detects that `global_integrations.json` and `global_security_policies.json` are both in `completed` state
- Depends on global_integrations and global_security completing first (not fully parallel with all Phase 7 agents)
- Triggered once (global granularity)

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | global_integrations.json and global_security_policies.json loaded | `log` |
| `CP-002` | All integration env vars extracted | `log` |
| `CP-003` | Security-related env vars added | `log` |
| `CP-004` | Core application vars (PORT, NODE_ENV, DATABASE_URL) added | `log` |
| `CP-005` | Sensitive variable without production default detected (correct behavior, just logging) | `log` |
| `CP-006` | .env.example template generated | `log` |
| `CP-007` | Environment config schema output generated and schema-validated | `notify` |

---

## Validation Criteria

- Every env var from global_integrations.json appears in the schema
- Every security-related config (JWT_SECRET, TOKEN_EXPIRY, CORS origins) appears as an env var
- Core vars (NODE_ENV, PORT, DATABASE_URL) are present
- All sensitive vars are marked sensitive=true
- No actual secret values appear in the output
- Development environment has defaults for non-sensitive vars
- Production environment has no defaults for sensitive vars
- Every var has type, description, and validation example
- .env.example contains all variables with safe values or placeholders
- Config validation rules cover required checks for production
- Output JSON passes schema validation

---

## Context Sources

- global_integrations.json (all integration env vars from global_integrations agent)
- global_security_policies.json (security config requiring env vars from global_security agent)
- All modules' contracts (database config, port config, module-specific settings)
- Standard environment variable patterns for Node.js/TypeScript applications

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` |

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | `node_write` MCP tool not yet built | this agent | Cannot write output with registry validation -- blocked |
| `TG-002` | `node_read` MCP tool not yet built | this agent | Cannot read upstream artifacts with field enforcement -- blocked |
| `TG-003` | `tracker_read` MCP tool not yet built | this agent | Cannot read pipeline state -- blocked |
| `TG-004` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |
| `TG-005` | Env var extractor that scans integration and security artifacts to automatically identify all needed variables | this agent | Must manually scan; risk of missing variables that cause runtime failures |
| `TG-006` | Config template generator that produces formatted .env.example with sections and comments | this agent | Must manually compose template; formatting inconsistencies |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `global-env-config` |
| `agentName` | ready | `global_env_config` |
| `agentRole` | ready | Environment Configuration Schema Builder |
| `agentDescription` | ready | Produces comprehensive env config schema with per-environment definitions, validation rules, and .env.example |
| `operationMode` | ready | autonomous, no fallback |
| `goal` | ready | Three objectives defined with clear priorities |
| `inputs` | ready | global_integrations.json, global_security_policies.json, module contracts |
| `guardrails` | ready | 15 rules covering constraints, quality, data handling, scope, universal tools, and completion signal |
| `scopeBoundary` | ready | 7 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | JSON output with full shape for environment_config_schema.json |
| `triggers` | ready | Triggered after global_integrations and global_security complete |
| `checkpoints` | ready | 7 checkpoints covering loading, extraction, and template generation |
| `validation` | ready | 11 validation criteria |
| `contextSources` | ready | 4 context sources listed |
| `metadata` | ready | Phase 7, global, autonomous, both modes |
