# DB Implementation Agent

> **Greek:** Chthōn (Chthṓn) — "earth/ground"
> **Sanskrit:** भूमि (Bhūmi) — "earth/foundation"
> **Tagline:** *"The ground truth of your data"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `db_impl` |
| Name | DB Implementation Agent |
| Phase | 10 — Implementation & Testing |
| Type | `pipeline` |
| Granularity | `per_module` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Implement the database layer for a module by generating Prisma schema additions, migration files, and seed scripts according to the approved pre-code plan and the prisma_contract — then commit the implementation atomically on the impl/db/{module_id} branch and update code_map.json.

| Priority | Objective |
|---|---|
| primary | Generate correct Prisma schema models that exactly match prisma_contract.json definitions including fields, relations, indexes, and constraints |
| secondary | Create migration files and seed scripts that populate initial data from production_bootstrap.json, following global_db_patterns conventions |
| tertiary | Update code_map.json with entries for every file created or modified, maintaining full traceability from contract to implementation |

---

## Inputs

### Global Analysis (optional enrichment)
- **Source:** `pre_code_global_analysis` agent via `node_read(input_key: "global_analysis")`
- **Required:** no — if available, follow its standards and shared element assignments. If unavailable, proceed with contract + baked-in defaults.
- **What it provides:**
  - `se` (shared_elements): Which shared models/utilities this module should CREATE vs IMPORT. If this module is listed in `se.cb` (created_by), create the shared element. If listed in `se.ub` (used_by), import it.
  - `ss` (system_standards): Project-specific patterns — `ss.da` (DB access pattern), `ss.eh` (error handling), `ss.fo` (file organization). Follow these over your own defaults.
  - `sf` (scaffolded_files): What already exists in the project. Do not recreate these files.

### prisma_contract.json
- **Source:** `db_contract` agent -> `agent_output/contracts/{module_id}/prisma_contract.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "models": {
    "type": "array",
    "description": "Prisma models to implement",
    "items": {
      "name": {
        "type": "string",
        "example": "User"
      },
      "fields": {
        "type": "array",
        "items": {
          "name": { "type": "string", "example": "email" },
          "type": { "type": "string", "example": "String" },
          "attributes": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["@unique"]
          },
          "optional": { "type": "boolean", "example": false },
          "default": { "type": "string | null", "example": null }
        }
      },
      "relations": {
        "type": "array",
        "items": {
          "name": { "type": "string", "example": "sessions" },
          "model": { "type": "string", "example": "Session" },
          "type": { "type": "string", "enum": ["one_to_one", "one_to_many", "many_to_many"] }
        }
      },
      "indexes": {
        "type": "array",
        "items": {
          "fields": { "type": "array", "items": { "type": "string" } },
          "unique": { "type": "boolean" }
        }
      },
      "story_refs": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["US-AUTH-001"]
      }
    }
  }
}
```

### global_db_patterns.json
- **Source:** `global_db_patterns` agent -> `agent_output/global/global_db_patterns.json`
- **Required:** yes
- **Shape:**
```json
{
  "naming_conventions": {
    "type": "object",
    "fields": {
      "table_name": { "type": "string", "example": "PascalCase for Prisma models" },
      "field_name": { "type": "string", "example": "camelCase" },
      "relation_name": { "type": "string", "example": "camelCase, plural for many" }
    }
  },
  "standard_fields": {
    "type": "object",
    "description": "Fields every model should have",
    "fields": {
      "id": { "type": "string", "example": "String @id @default(cuid())" },
      "createdAt": { "type": "string", "example": "DateTime @default(now())" },
      "updatedAt": { "type": "string", "example": "DateTime @updatedAt" }
    }
  },
  "soft_delete": {
    "type": "object",
    "description": "Soft delete pattern configuration",
    "fields": {
      "enabled": { "type": "boolean", "example": true },
      "field_name": { "type": "string", "example": "deletedAt" },
      "field_type": { "type": "string", "example": "DateTime?" }
    }
  },
  "audit_fields": {
    "type": "object",
    "description": "Audit trail fields",
    "fields": {
      "createdBy": { "type": "string", "example": "String?" },
      "updatedBy": { "type": "string", "example": "String?" }
    }
  },
  "index_conventions": {
    "type": "array",
    "description": "Standard indexing patterns",
    "items": {
      "pattern": { "type": "string", "example": "Always index foreign keys" },
      "applies_to": { "type": "string", "example": "All relation fields" }
    }
  }
}
```

### db_flow.json
- **Source:** `db_interaction` agent -> `agent_output/architecture/{module_id}/db_flow.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "db_nodes": {
    "type": "array",
    "items": {
      "node_id": { "type": "string" },
      "model_ref": { "type": "string" },
      "operation": { "type": "string", "enum": ["create", "read", "update", "delete", "upsert", "aggregate"] },
      "story_ref": { "type": "string" }
    }
  }
}
```

### production_bootstrap.json
- **Source:** `production_bootstrap` agent -> `agent_output/global/production_bootstrap.json`
- **Required:** yes
- **Shape:**
```json
{
  "seed_data": {
    "type": "object",
    "description": "Initial data for seeding",
    "fields": {
      "roles": { "type": "array" },
      "permissions": { "type": "array" },
      "admin_user": { "type": "object" },
      "config_entries": { "type": "array" }
    }
  }
}
```

---

## Outputs

### Actual Code Files
- **Path:** Project directory (prisma/ and related paths)
- **Format:** Prisma schema, SQL migrations, TypeScript seed scripts
- **Consumers:** `db_test`, `be_impl`, `architecture_sync`
- **Shape:**
```json
{
  "files_produced": {
    "type": "array",
    "description": "All files created or modified by this agent",
    "items": {
      "path": {
        "type": "string",
        "example": "prisma/schema.prisma"
      },
      "action": {
        "type": "string",
        "enum": ["created", "modified"],
        "example": "modified"
      },
      "content_type": {
        "type": "string",
        "enum": ["prisma_schema", "sql_migration", "typescript_seed", "typescript_utility"],
        "example": "prisma_schema"
      },
      "contract_ref": {
        "type": "string",
        "example": "prisma_contract.json#User"
      },
      "story_refs": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["US-AUTH-001"]
      }
    }
  },
  "git_state": {
    "type": "object",
    "fields": {
      "branch": {
        "type": "string",
        "example": "impl/db/auth"
      },
      "commit_message": {
        "type": "string",
        "example": "[db_impl] auth: create users and sessions tables with seed data"
      },
      "parent_branch": {
        "type": "string",
        "example": "scaffold/run-2026-03-21-001"
      }
    }
  }
}
```

### code_map.json (updated)
- **Path:** `code_map.json` (project root)
- **Format:** `json`
- **Consumers:** `pre_code_analysis` (future runs), `architecture_sync`, `be_impl`
- **Shape:**
```json
{
  "modules": {
    "type": "object",
    "description": "Updated with DB layer entries",
    "example": {
      "auth": {
        "db": {
          "files": [
            {
              "path": "prisma/schema.prisma",
              "type": "schema",
              "contract_ref": "prisma_contract.json",
              "story_ref": "US-AUTH-001",
              "created_by": "db_impl",
              "action": "modified"
            }
          ]
        }
      }
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `pre_code_analysis` | `pre_code_plan_db.json` (approved) | Implementation plan must be approved before any code is written |
| input | `db_contract` | `prisma_contract.json` | Contract defines what models, fields, and relations to implement |
| input | `global_db_patterns` | `global_db_patterns.json` | Naming, indexing, audit, and soft delete conventions |
| input | `db_interaction` | `db_flow.json` | DB operation flow for understanding data access patterns |
| input | `production_bootstrap` | `production_bootstrap.json` | Seed data for creating seed scripts |
| input | `impl_prep` | Prepared project | Base Prisma config to extend |

| Blocks | Agent | Why |
|---|---|---|
| output | `db_test` | DB tests require implemented schema and migrations to test against |
| output | `be_impl` | BE implementation depends on DB models being available (via Prisma client) |

---

## Orchestrator Communication

> Reference: `v2/architecture/agent-orchestrator-communication.md`

### Agent Identity

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

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | `md.a` | Read active modules to know which modules to process |
| 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: "db_impl", status: "completed")`
- **On failure:** `tracker_update(agent_id: "db_impl", status: "failed", add_intervention: { id: "...", agent_id: "db_impl", type: "error", message: "..." })`

### Scope Resolution

Per-module agent — reads `md.a` (modules.active) from tracker via `tracker_read`. Processes only active modules, skips already-completed ones.

```
1. tracker_read(agent_id: "db_impl", fields: ["md.a"])
   -> { "md": { "a": ["auth"] } }
2. For each module in active list:
   a. node_read(agent_id: "db_impl", input_key: "pre_code_plan_db", unit_id: "auth")
   b. node_read(agent_id: "db_impl", input_key: "prisma_contract", unit_id: "auth")
   c. Implement DB layer -> generate schema, migrations, seeds
   d. node_write(agent_id: "db_impl", output_key: "db_code", data: {...}, unit_id: "auth")
3. tracker_update(agent_id: "db_impl", status: "completed")
```

---

## Compressed Keymap

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

**db_impl_result.json**

| Key | Full Name | Description |
|---|---|---|
| `fp` | files_produced | Array of files produced |
| `fp.pt` | path | File path |
| `fp.ac` | action | Action taken (created/modified) |
| `fp.ct` | content_type | Content type (migration/seed/model/schema) |
| `fp.cr` | contract_ref | Contract reference |
| `fp.sr` | story_refs | Story references implemented |
| `gs` | git_state | Git state object |
| `gs.br` | branch | Git branch name |
| `gs.cm` | commit_message | Commit message |
| `gs.pb` | parent_branch | Parent branch name |
| `cm` | code_map | Updated code map reference |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write DB implementation output via registry-validated compressed keys. Agent calls `node_write(agent_id: "db_impl", output_key: "db_code", data: {...}, unit_id: "{module_id}")`. | Pending |
| `node_read` | Read upstream artifacts (pre_code_plan, prisma_contract, global_db_patterns, db_flow, production_bootstrap). Agent calls `node_read(agent_id: "db_impl", input_key: "prisma_contract", unit_id: "{module_id}")`. | Pending |
| `tracker_read` | Read active modules. Agent calls `tracker_read(agent_id: "db_impl", fields: ["md.a"])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "db_impl", status: "completed")`. | Pending |
| `git_operations` | Branch creation, file staging, atomic commit | yes |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must follow global_db_patterns for naming conventions, index conventions, audit fields, and soft delete pattern. |
| R-002 | `constraint` | `must` | Must create migration files — not just modify the schema. Migrations are required for reproducible database setup. |
| R-003 | `constraint` | `must` | Must include seed data from production_bootstrap.json in seed scripts. Initial data must be loadable. |
| R-004 | `constraint` | `must` | Must commit atomically — all DB implementation files in a single commit on impl/db/{module_id} branch. |
| R-005 | `constraint` | `must` | Must only proceed if pre_code_plan_db.json has approved=true. Never implement without approval. |
| R-006 | `data_handling` | `must` | For retrofit mode: must respect change_type. modify_existing = ALTER TABLE (not recreate), extend_existing = additive only, no_change_reference = skip. |
| R-007 | `output_quality` | `must` | Must update code_map.json with entries for every file created or modified, including contract_ref and story_ref. |
| R-008 | `output_quality` | `should` | Standard fields (id, createdAt, updatedAt) should be added to every model per global_db_patterns. |
| R-009 | `output_quality` | `should` | Commit message should follow convention: [db_impl] {module_id}: {summary} |
| R-010 | `scope_boundary` | `must` | Must not implement routes, services, or UI. DB layer only. |
| R-011 | `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-012 | `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-013 | `constraint` | `must` | Must call `tracker_update(agent_id: "db_impl", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "db_impl", status: "failed", add_intervention: {...})` before exiting on failure. |
| R-014 | `constraint` | `must` | Must read active modules via `tracker_read(agent_id: "db_impl", fields: ["md.a"])` and process only active modules. Must not hardcode module lists. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 16384 |
| max_models_per_module | 20 |
| timeout_seconds | 300 |

---

## Scope Boundary

**In scope:**
- Generating Prisma schema model definitions
- Creating SQL migration files
- Creating TypeScript seed scripts
- Applying global DB patterns (naming, indexes, audit fields, soft delete)
- Updating code_map.json with DB layer entries
- Creating git branch and atomic commit
- Following the approved pre_code_plan
- In fixation mode: reading test report, targeting only failing tests, applying minimal fixes without full regeneration

**Out of scope:**
- Implementing API routes or services (be_impl does this)
- Implementing UI components (fe_impl does this)
- Running tests (db_test does this)
- Running migrations against a database (done at deployment/test time)
- Modifying global_db_patterns
- Making schema design decisions (those come from db_contract)

---

## Triggers

- Orchestrator activates this agent when pre_code_plan_db.json for the module has approved=true
- Module order follows module_priority_sequence.json
- In retrofit mode, triggered only for modules with DB layer changes
- In fixation mode (inner retry loop), re-triggered by orchestrator when db_test fails and retry count < 3 — receives test_output/{module_id}/db/report.json as additional input, targets only failing tests
- In fixation mode (Phase 11 fix planner), re-triggered with fix_plan_{module_id}.json containing specific fix directives for the DB layer
- In bugfix pipeline, triggered with diagnosis.json context and fix_plan targeting only diagnosed DB issues

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | Approved pre_code_plan_db.json loaded | `log` |
| `CP-002` | Prisma contract and global patterns loaded | `log` |
| `CP-003` | Prisma schema models generated | `log` |
| `CP-004` | Migration files created | `log` |
| `CP-005` | Seed scripts generated from production_bootstrap | `log` |
| `CP-006` | code_map.json updated with DB entries | `log` |
| `CP-007` | Git branch created and atomic commit made | `notify` — DB implementation complete, db_test can proceed |

---

## Validation Criteria

- Prisma schema is syntactically valid (would pass `prisma validate`)
- Every model in prisma_contract.json is present in the schema
- Every model has standard fields (id, createdAt, updatedAt) per global_db_patterns
- Migration files exist for all schema changes
- Seed script references valid models and fields
- Git commit exists on impl/db/{module_id} branch
- code_map.json has entries for every file created or modified
- All entries in code_map.json have valid contract_ref values
- Commit message follows the [db_impl] convention

---

## Context Sources

- pre_code_plan_db.json (approved implementation plan)
- prisma_contract.json (model definitions)
- global_db_patterns.json (conventions)
- db_flow.json (data access patterns)
- production_bootstrap.json (seed data)
- Existing prisma/schema.prisma from impl_prep

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if DB implementation fails, BE and FE cannot proceed for this module |

---

## 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 active modules -- blocked |
| `TG-004` | `tracker_update` MCP tool not yet built | this agent | Cannot report completion -- blocked |
| `TG-005` | Prisma schema generator that produces syntactically correct Prisma model definitions from contract JSON | this agent | Manual Prisma syntax construction risks syntax errors and missing attributes |
| `TG-006` | Migration generator that creates SQL DDL statements (CREATE TABLE, ALTER TABLE, CREATE INDEX) from schema diffs | this agent | Manual SQL writing risks syntax errors and missing constraints |
| `TG-007` | Code map updater that atomically appends entries to code_map.json without corrupting existing entries | this agent | Manual JSON updates risk format corruption and merge conflicts |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `db-impl` |
| `agentName` | ready | `db_impl` |
| `agentRole` | ready | "Database Schema and Migration Generator" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | 6 inputs: pre_code_plan (approved), prisma_contract, global_db_patterns, db_flow, production_bootstrap, scaffolded project |
| `guardrails` | ready | 14 rules defined across constraint, data_handling, output_quality, scope_boundary categories |
| `scopeBoundary` | ready | 7 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | Prisma schema, SQL migrations, TypeScript seed scripts, code_map updates |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 7 checkpoints with actions |
| `validation` | ready | 9 validation criteria |
| `contextSources` | ready | 6 context sources |
| `metadata` | ready | phase: "10", mode: "all", granularity: "per_module" |
