# Production Bootstrap Agent

> **Greek:** Genesis (Genesis) -- "origin/birth"
> **Sanskrit:** Utpatti (Utpatti) -- "genesis/origin"
> **Tagline:** *"From schema to seed, ready for reality"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `production_bootstrap` |
| Name | Production Bootstrap Agent |
| Phase | 7 -- Global Architecture |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `interactive` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Generate the complete production bootstrap configuration including roles, permissions, RBAC matrix, seed data for lookup tables, admin user template, and system settings, producing everything needed to initialize the application database and auth system for first deployment.

| Priority | Objective |
|---|---|
| primary | Define complete role and permission structures with an RBAC matrix, deriving from global security policies and validating against all modules' resource requirements |
| secondary | Generate seed data templates for all lookup tables, enums, and reference data that must exist before the application can function |
| tertiary | Provide admin user template and system settings configuration for first-time application setup |

---

## Inputs

### global_security_policies.json
- **Source:** `global_security` -> `agent_output/architecture/global/global_security_policies.json`
- **Required:** no (conditional — only present if global_security ran; if absent (no auth needed), RBAC/role sections are omitted from bootstrap output)
- **Shape:**
```json
{
  "rbac": {
    "roles": [
      {
        "role_id": "string",
        "name": "string",
        "description": "string",
        "is_default": "boolean",
        "is_admin": "boolean",
        "inherits_from": "string | null"
      }
    ],
    "permissions": [
      {
        "permission_id": "string",
        "resource": "string",
        "actions": ["string"],
        "description": "string",
        "module_id": "string"
      }
    ],
    "role_permission_map": {
      "admin": ["string -- permission_ids"],
      "user": ["string -- permission_ids"]
    }
  },
  "auth_strategy": {
    "type": "string",
    "config": {}
  }
}
```

### prisma_contract.json (ALL modules)
- **Source:** `db_contract` -> `agent_output/contracts/{module_id}/prisma_contract.json` (for each module)
- **Required:** yes
- **Shape:**
```json
{
  "module_id": "string",
  "models": [
    {
      "model_name": "string",
      "table_name": "string",
      "fields": [
        {
          "field_name": "string",
          "type": "string",
          "attributes": ["string"]
        }
      ]
    }
  ],
  "enums": [
    {
      "enum_name": "string",
      "values": ["string"]
    }
  ]
}
```

### global_db_patterns.json
- **Source:** `global_db_patterns` -> `agent_output/architecture/global/global_db_patterns.json`
- **Required:** no (conditional — only present if global_db_patterns ran and DB layer exists; if absent, enum seeding and audit fields are omitted from bootstrap output)
- **Shape:**
```json
{
  "shared_enums": [
    {
      "enum_name": "string",
      "values": ["string"],
      "used_by_modules": ["string"]
    }
  ],
  "soft_delete_strategy": {
    "enabled": "boolean",
    "models_using_soft_delete": ["string"]
  },
  "audit_fields": {
    "standard_fields": [
      {
        "field_name": "string",
        "type": "string",
        "default": "string"
      }
    ]
  }
}
```

---

## Outputs

### production_bootstrap.json
- **Path:** `agent_output/architecture/global/production_bootstrap.json`
- **Format:** `json`
- **Consumers:** `architect_reconcile`, `impl_prep`, `db_impl`
- **Shape:**
```json
{
  "generated_at": "string -- ISO-8601 timestamp",
  "total_roles": "number -- total roles defined",
  "total_permissions": "number -- total permissions defined",
  "total_seed_models": "number -- total models with seed data",
  "roles": [
    {
      "role_id": "string -- unique role identifier (e.g., 'ROLE-001')",
      "name": "string -- role name (e.g., 'admin', 'user', 'manager', 'moderator')",
      "display_name": "string -- human-readable name (e.g., 'System Administrator')",
      "description": "string -- what this role represents and what access it grants",
      "is_default": "boolean -- true if assigned to new users automatically",
      "is_admin": "boolean -- true if this role has full system access",
      "is_system": "boolean -- true if this role cannot be deleted or modified by users",
      "inherits_from": "string | null -- parent role_id for permission inheritance",
      "created_by": "string -- 'system' for bootstrap roles",
      "module_access": ["string -- module_ids this role can access (empty = all for admin)"]
    }
  ],
  "permissions": [
    {
      "permission_id": "string -- unique permission identifier (e.g., 'PERM-001')",
      "resource": "string -- the resource this permission applies to (e.g., 'users', 'invoices')",
      "resource_display": "string -- human-readable resource name",
      "actions": ["string -- 'create' | 'read' | 'update' | 'delete' | 'list' | 'export' | 'import' | 'manage'"],
      "description": "string -- what this permission allows",
      "module_id": "string -- which module owns this resource",
      "is_system": "boolean -- true if this permission cannot be modified",
      "conditions": {
        "own_only": "boolean -- whether this permission only applies to user's own records",
        "field_restrictions": ["string | null -- fields this permission excludes access to"]
      }
    }
  ],
  "role_permission_matrix": [
    {
      "role_id": "string -- role identifier",
      "role_name": "string -- role name for readability",
      "permissions": [
        {
          "permission_id": "string -- permission identifier",
          "resource": "string -- resource name for readability",
          "actions": ["string -- granted actions"],
          "conditions": {
            "own_only": "boolean",
            "field_restrictions": ["string | null"]
          }
        }
      ],
      "total_permissions": "number -- count of permissions for this role"
    }
  ],
  "seed_data": {
    "description": "string -- overview of seed data purpose",
    "models": [
      {
        "model_name": "string -- Prisma model name",
        "table_name": "string -- database table name",
        "module_id": "string -- module this model belongs to",
        "seed_type": "string -- 'lookup' | 'enum' | 'reference' | 'system_config' | 'initial_data'",
        "records": [
          {
            "field_values": {
              "field_name": "string | number | boolean -- value for each field"
            },
            "description": "string -- why this record is needed"
          }
        ],
        "depends_on": ["string | null -- model names that must be seeded first"]
      }
    ],
    "seed_order": ["string -- model names in the order they should be seeded (respecting dependencies)"]
  },
  "admin_user_template": {
    "description": "string -- template for creating the first admin user",
    "fields": {
      "email": "string -- placeholder (e.g., 'admin@example.com')",
      "password": "string -- instruction (e.g., 'SET_SECURE_PASSWORD -- must be changed on first login')",
      "name": "string -- placeholder (e.g., 'System Administrator')",
      "role": "string -- role_id for admin role"
    },
    "setup_instructions": [
      {
        "step": "number -- step order",
        "instruction": "string -- what to do",
        "important": "boolean -- whether this step is critical"
      }
    ],
    "security_notes": [
      "string -- security reminders (e.g., 'Change default password immediately', 'Enable 2FA')"
    ]
  },
  "system_settings": {
    "description": "string -- application-wide settings that must be configured",
    "settings": [
      {
        "setting_id": "string -- unique setting identifier",
        "key": "string -- setting key (e.g., 'app.name', 'app.defaultLocale')",
        "value": "string -- default value",
        "type": "string -- 'string' | 'number' | 'boolean' | 'json'",
        "category": "string -- 'general' | 'email' | 'notifications' | 'security' | 'display'",
        "description": "string -- what this setting controls",
        "user_configurable": "boolean -- whether end-users can change this",
        "requires_restart": "boolean -- whether changing this requires app restart"
      }
    ]
  },
  "migration_checklist": {
    "description": "string -- checklist for production deployment",
    "pre_seed": [
      {
        "step": "number",
        "task": "string -- what to do before seeding",
        "critical": "boolean"
      }
    ],
    "post_seed": [
      {
        "step": "number",
        "task": "string -- what to do after seeding",
        "critical": "boolean"
      }
    ]
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `global_security` | `global_security_policies.json` | Provides RBAC model with roles, permissions, and role-permission map |
| input | `db_contract` (all modules) | `prisma_contract.json` | Provides model definitions and enums for seed data generation |
| input | `global_db_patterns` | `global_db_patterns.json` | Provides shared enums and audit field patterns for consistent seeding |
| barrier | ALL Phase 6 agents | All modules must complete Phase 6 before this global agent starts |

| Blocks | Agent | Why |
|---|---|---|
| output | `architect_reconcile` | Reconcile needs bootstrap config for complete architecture |
| output | `impl_prep` | Impl prep agent uses bootstrap to generate seed scripts |
| output | `db_impl` | DB implementation uses seed data and RBAC for initial migration |

---

## Orchestrator Communication

### Agent Identity

This agent's ID is `production_bootstrap`. 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: "production_bootstrap", status: "completed")`
- **On failure:** `tracker_update(agent_id: "production_bootstrap", status: "failed", add_intervention: { id: "...", agent_id: "production_bootstrap", type: "error", message: "..." })`

### Scope Resolution

Global agent -- does NOT read `md.a`. Reads global and per-module artifacts from upstream agents.

```
1. node_read(agent_id: "production_bootstrap", input_key: "global_security_policies") — optional, may return NR-009
2. node_read(agent_id: "production_bootstrap", input_key: "prisma_contract_all")
3. node_read(agent_id: "production_bootstrap", input_key: "global_db_patterns") — optional, may return NR-009
4. Process all inputs → generate bootstrap config
5. node_write(agent_id: "production_bootstrap", output_key: "production_bootstrap", data: {...})
6. tracker_update(agent_id: "production_bootstrap", status: "completed")
```

---

## Compressed Keymap

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

### Output: `production_bootstrap.json`

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | ISO-8601 timestamp |
| `tr` | total_roles | Total roles defined |
| `tp` | total_permissions | Total permissions defined |
| `ts` | total_seed_models | Total models with seed data |
| `rl` | roles | Array of role definitions |
| `rl.ri` | role_id | Unique role ID (e.g., 'ROLE-001') |
| `rl.nm` | name | Role name (e.g., 'admin') |
| `rl.dn` | display_name | Human-readable name (e.g., 'System Administrator') |
| `rl.ds` | description | What this role represents |
| `rl.id` | is_default | Assigned to new users automatically |
| `rl.ia` | is_admin | Has full system access |
| `rl.is` | is_system | Cannot be deleted or modified by users |
| `rl.ih` | inherits_from | Parent role_id for permission inheritance |
| `rl.cb` | created_by | Always 'system' for bootstrap roles |
| `rl.ma` | module_access | Module IDs this role can access |
| `pm` | permissions | Array of permission definitions |
| `pm.pi` | permission_id | Unique permission ID (e.g., 'PERM-001') |
| `pm.rs` | resource | Resource name (e.g., 'users') |
| `pm.rd` | resource_display | Human-readable resource name |
| `pm.ac` | actions | Allowed actions (create, read, update, etc.) |
| `pm.ds` | description | What this permission allows |
| `pm.mi` | module_id | Module that owns this resource |
| `pm.is` | is_system | Cannot be modified |
| `pm.cn` | conditions | Permission conditions |
| `pm.cn.oo` | own_only | Only applies to user's own records |
| `pm.cn.fr` | field_restrictions | Fields this permission excludes |
| `rm` | role_permission_matrix | Complete role-permission mapping |
| `rm.ri` | role_id | Role identifier |
| `rm.rn` | role_name | Role name for readability |
| `rm.pm` | permissions | Permissions granted to this role |
| `rm.pm.pi` | permission_id | Permission identifier |
| `rm.pm.rs` | resource | Resource name for readability |
| `rm.pm.ac` | actions | Granted actions |
| `rm.pm.cn` | conditions | Conditions on this grant |
| `rm.pm.cn.oo` | own_only | Own records only |
| `rm.pm.cn.fr` | field_restrictions | Field restrictions |
| `rm.tp` | total_permissions | Count of permissions for this role |
| `sd` | seed_data | Seed data configuration |
| `sd.ds` | description | Overview of seed data purpose |
| `sd.md` | models | Array of models with seed data |
| `sd.md.mn` | model_name | Prisma model name |
| `sd.md.tn` | table_name | Database table name |
| `sd.md.mi` | module_id | Module this model belongs to |
| `sd.md.st` | seed_type | lookup / enum / reference / system_config / initial_data |
| `sd.md.rc` | records | Array of seed records |
| `sd.md.rc.fv` | field_values | Field name-value pairs |
| `sd.md.rc.ds` | description | Why this record is needed |
| `sd.md.dp` | depends_on | Models that must be seeded first |
| `sd.so` | seed_order | Model names in seeding order |
| `au` | admin_user_template | Admin user setup template |
| `au.ds` | description | Template purpose description |
| `au.fd` | fields | Template field values |
| `au.fd.em` | email | Placeholder email |
| `au.fd.pw` | password | Instruction placeholder |
| `au.fd.nm` | name | Placeholder name |
| `au.fd.rl` | role | Role ID for admin |
| `au.si` | setup_instructions | Admin setup steps |
| `au.si.sp` | step | Step order |
| `au.si.in` | instruction | What to do |
| `au.si.im` | important | Whether step is critical |
| `au.sn` | security_notes | Security reminders |
| `ss` | system_settings | Application-wide settings |
| `ss.ds` | description | Settings overview |
| `ss.st` | settings | Array of settings |
| `ss.st.si` | setting_id | Unique setting identifier |
| `ss.st.ky` | key | Setting key (e.g., 'app.name') |
| `ss.st.vl` | value | Default value |
| `ss.st.tp` | type | string / number / boolean / json |
| `ss.st.ct` | category | general / email / notifications / security / display |
| `ss.st.ds` | description | What this setting controls |
| `ss.st.uc` | user_configurable | Whether end-users can change this |
| `ss.st.rr` | requires_restart | Whether changing requires restart |
| `mc` | migration_checklist | Production deployment checklist |
| `mc.ds` | description | Checklist overview |
| `mc.ps` | pre_seed | Pre-seed tasks |
| `mc.ps.sp` | step | Step number |
| `mc.ps.tk` | task | What to do before seeding |
| `mc.ps.cr` | critical | Whether critical |
| `mc.po` | post_seed | Post-seed tasks |
| `mc.po.sp` | step | Step number |
| `mc.po.tk` | task | What to do after seeding |
| `mc.po.cr` | critical | Whether critical |

---

## Tools Required

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

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must define at least admin and default user roles |
| R-002 | `constraint` | `must` | Must have seed data for all lookup tables and shared enums |
| R-003 | `constraint` | `must` | Must include admin user template with setup instructions |
| R-004 | `not_allowed` | `must` | Must NOT include real credentials, passwords, or API keys in seed data |
| R-005 | `constraint` | `must` | Admin user template password must be a placeholder with instruction to change |
| R-006 | `constraint` | `must` | Seed data order must respect model dependencies (foreign keys) |
| R-007 | `data_handling` | `must` | Every permission must reference a valid resource from a known module |
| R-008 | `output_quality` | `must` | Role-permission matrix must cover all roles and all permissions with no gaps |
| R-009 | `interaction` | `should` | Should ask user for confirmation on role names and default permissions when unclear |
| R-010 | `output_quality` | `should` | System settings should cover common application configuration needs |
| R-011 | `scope_boundary` | `should` | Migration checklist should include pre-seed and post-seed verification steps |
| R-012 | `constraint` | `must` | System roles (admin, default user) must be marked is_system=true and cannot be deleted |
| 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: "production_bootstrap", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "production_bootstrap", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32000 |
| max_roles | 20 |
| max_permissions | 200 |
| max_seed_records_per_model | 100 |

---

## Scope Boundary

**In scope:**
- Defining roles with display names, descriptions, and inheritance
- Defining permissions with resource/action granularity and conditions
- Building role-permission matrix
- Generating seed data for lookup tables, enums, and reference data
- Providing admin user template with security instructions
- Defining system settings for application configuration
- Creating migration checklist for production deployment
- Asking user for clarification on role/permission decisions

**Out of scope:**
- Implementing seed scripts (Phase 10 DB implementation)
- Creating actual database records
- Managing real user accounts or credentials
- Modifying security policies (read-only from global_security)
- Defining middleware or endpoint security (already done in earlier phases)
- Infrastructure provisioning or deployment configuration

---

## Triggers

- Orchestrator detects that the relevant global outputs are in `completed` state (or confirmed skipped). If global_security or global_db_patterns were skipped, production_bootstrap proceeds with whatever global outputs are available
- Depends on global_security and global_db_patterns completing first
- Triggered once (global granularity)

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All input artifacts loaded -- security policies, prisma contracts, db patterns | `log` |
| `CP-002` | Roles defined -- asking user for confirmation on custom role names | `pause` |
| `CP-003` | Permissions extracted from all modules | `log` |
| `CP-004` | Role-permission matrix complete | `log` |
| `CP-005` | Seed data generated for all lookup tables and enums | `log` |
| `CP-006` | Admin user template created -- asking user to verify template fields | `pause` |
| `CP-007` | Production bootstrap output generated and schema-validated | `notify` |

---

## Validation Criteria

- At least admin and default user roles are defined
- Admin role has is_admin=true and is_system=true
- Default user role has is_default=true
- Every permission references a valid module_id
- Role-permission matrix covers all roles and all permissions
- No orphan permissions (permissions not assigned to any role)
- Seed data exists for all shared enums from global_db_patterns
- Seed data order respects model dependencies
- Admin user template has placeholder password with change instruction
- No real credentials or secrets in any output field
- System settings cover at least app name and default locale
- Output JSON passes schema validation

---

## Context Sources

- global_security_policies.json (RBAC model, auth strategy from global_security agent)
- prisma_contract.json from all modules (model definitions, enums for seed data)
- global_db_patterns.json (shared enums, audit fields from global_db_patterns agent)
- User conversation (for interactive role/permission confirmation)
- Common RBAC patterns for web applications

---

## Operation Mode

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

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | RBAC matrix generator that automatically builds complete role-permission matrix from security policies | this agent | Must manually construct matrix; risk of missing permissions or inconsistent grants |
| `TG-002` | Seed data template generator that creates seed records from Prisma model definitions and enums | this agent | Must manually create seed records; risk of missing required lookup data |
| `TG-003` | Conversation handler for interactive role/permission confirmation with user | this agent | Must make best-guess decisions; lower quality role definitions |
| `TG-004` | `node_write` MCP tool not yet built | this agent | Cannot write output with registry validation -- blocked |
| `TG-005` | `node_read` MCP tool not yet built | this agent | Cannot read upstream artifacts with field enforcement -- blocked |
| `TG-006` | `tracker_read` MCP tool not yet built | this agent | Cannot read pipeline state -- blocked |
| `TG-007` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `production-bootstrap` |
| `agentName` | ready | `production_bootstrap` |
| `agentRole` | ready | Production Bootstrap Configurator |
| `agentDescription` | ready | Generates roles, permissions, RBAC matrix, seed data, and admin template for production deployment |
| `operationMode` | ready | interactive, no fallback |
| `goal` | ready | Three objectives defined with clear priorities |
| `inputs` | ready | global_security_policies.json, all prisma_contract.json, global_db_patterns.json |
| `guardrails` | ready | 15 rules covering constraints, quality, data handling, interaction, universal tools, and completion signal |
| `scopeBoundary` | ready | 8 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | JSON output with full shape for production_bootstrap.json |
| `triggers` | ready | Triggered after global_security and global_db_patterns complete |
| `checkpoints` | ready | 7 checkpoints with 2 pause points for user interaction |
| `validation` | ready | 12 validation criteria |
| `contextSources` | ready | 5 context sources listed |
| `metadata` | ready | Phase 7, global, interactive, both modes |
