# BE Implementation Agent

> **Greek:** Ergon (Érgon) — "work/deed"
> **Sanskrit:** कर्म (Karma) — "action/work"
> **Tagline:** *"Where logic becomes reality"*

---

## Agent Identity

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

---

## Goal & Objectives

**Goal:** Implement the backend layer for a module by generating API routes, services, and middleware wiring according to the approved pre-code plan and the OpenAPI contract — ensuring all endpoints are implemented, middleware is correctly applied per the policy flow, shared services from the global registry are used, and security policies are honored — then commit atomically and update code_map.json.

| Priority | Objective |
|---|---|
| primary | Implement ALL endpoints from openapi.json with correct request validation, response shapes, error handling, and HTTP status codes |
| secondary | Wire middleware per be_policy_flow.json and use shared services from global_services_registry — never duplicating globally defined middleware or services |
| tertiary | Follow global_security_policies for authentication, authorization, and data protection on every endpoint that requires it |

---

## 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 middleware/services/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.ah` (auth pattern), `ss.eh` (error handling), `ss.rf` (response format), `ss.fo` (file organization). Follow these over your own defaults.
  - `sf` (scaffolded_files): What already exists in the project. Do not recreate these files.

### openapi.json
- **Source:** `be_contract` agent -> `agent_output/contracts/{module_id}/openapi.json`
- **Required:** yes
- **Shape:**
```json
{
  "openapi": {
    "type": "string",
    "example": "3.0.3"
  },
  "info": {
    "type": "object",
    "fields": {
      "title": { "type": "string", "example": "Auth Module API" },
      "version": { "type": "string", "example": "1.0.0" }
    }
  },
  "paths": {
    "type": "object",
    "description": "OpenAPI path definitions with operations",
    "example": {
      "/api/auth/login": {
        "post": {
          "operationId": "loginUser",
          "summary": "Authenticate user",
          "requestBody": {
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "email": { "type": "string" },
                    "password": { "type": "string" }
                  },
                  "required": ["email", "password"]
                }
              }
            }
          },
          "responses": {
            "200": { "description": "Login successful" },
            "401": { "description": "Invalid credentials" }
          },
          "x-story-ref": "US-AUTH-001"
        }
      }
    }
  },
  "components": {
    "type": "object",
    "description": "Reusable schemas, security schemes, parameters"
  }
}
```

### be_policy_flow.json
- **Source:** `be_policy` agent -> `agent_output/architecture/{module_id}/be_policy_flow.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string", "example": "auth" },
  "policy_nodes": {
    "type": "array",
    "items": {
      "node_id": { "type": "string" },
      "endpoint_ref": { "type": "string", "example": "POST /api/auth/login" },
      "middleware_chain": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["rateLimit", "validateBody"]
      },
      "service_ref": { "type": "string", "example": "auth.service.ts:login" },
      "story_ref": { "type": "string" },
      "auth_required": { "type": "boolean", "example": false },
      "roles_allowed": {
        "type": "array | null",
        "items": { "type": "string" },
        "example": null
      }
    }
  }
}
```

### global_services_registry.json
- **Source:** `global_services` agent -> `agent_output/global/global_services_registry.json`
- **Required:** yes
- **Shape:**
```json
{
  "services": {
    "type": "array",
    "description": "Shared services available across modules",
    "items": {
      "service_id": { "type": "string", "example": "emailService" },
      "name": { "type": "string", "example": "Email Service" },
      "path": { "type": "string", "example": "src/services/shared/email.service.ts" },
      "methods": {
        "type": "array",
        "items": {
          "name": { "type": "string" },
          "params": { "type": "array" },
          "returns": { "type": "string" }
        }
      },
      "used_by_modules": { "type": "array", "items": { "type": "string" } }
    }
  }
}
```

### global_middleware_registry.json
- **Source:** `global_middleware` agent -> `agent_output/global/global_middleware_registry.json`
- **Required:** yes
- **Shape:**
```json
{
  "middleware": {
    "type": "array",
    "items": {
      "middleware_id": { "type": "string" },
      "name": { "type": "string" },
      "type": { "type": "string" },
      "applies_to": { "type": "string" },
      "path": { "type": "string", "example": "src/middleware/authGuard.ts" }
    }
  }
}
```

### global_security_policies.json
- **Source:** `global_security` agent -> `agent_output/global/global_security_policies.json`
- **Required:** yes
- **Shape:**
```json
{
  "auth_strategy": {
    "type": "string",
    "example": "JWT Bearer tokens"
  },
  "policies": {
    "type": "array",
    "items": {
      "policy_id": { "type": "string", "example": "SEC-001" },
      "name": { "type": "string", "example": "Authentication Required" },
      "description": { "type": "string" },
      "applies_to": {
        "type": "string",
        "enum": ["all_endpoints", "protected_endpoints", "admin_endpoints"],
        "example": "protected_endpoints"
      },
      "implementation": {
        "type": "string",
        "description": "How to implement this policy",
        "example": "Apply authGuard middleware to all routes except /auth/login and /auth/register"
      }
    }
  },
  "rbac": {
    "type": "object",
    "description": "Role-based access control configuration",
    "fields": {
      "roles": { "type": "array", "items": { "type": "string" } },
      "default_role": { "type": "string" }
    }
  }
}
```

### module_flow.json
- **Source:** `architect_reconcile` agent -> `agent_output/reconciliation/{module_id}/module_flow.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": { "type": "string" },
  "layers": { "type": "object" },
  "cross_layer_links": { "type": "array" },
  "cross_module_dependencies": { "type": "array" }
}
```

---

## Outputs

### Actual Code Files
- **Path:** Project directory (src/routes/, src/services/, src/middleware/)
- **Format:** TypeScript source files
- **Consumers:** `be_test`, `fe_impl`, `architecture_sync`
- **Shape:**
```json
{
  "files_produced": {
    "type": "array",
    "description": "All files created or modified",
    "items": {
      "path": {
        "type": "string",
        "example": "src/routes/auth.ts"
      },
      "action": {
        "type": "string",
        "enum": ["created", "modified"]
      },
      "content_type": {
        "type": "string",
        "enum": ["route", "service", "middleware", "validator", "utility", "type_definition"],
        "example": "route"
      },
      "contract_ref": {
        "type": "string",
        "example": "openapi.json#/auth/login"
      },
      "story_refs": {
        "type": "array",
        "items": { "type": "string" }
      },
      "endpoints_implemented": {
        "type": "array",
        "description": "Which endpoints this file implements",
        "items": { "type": "string" },
        "example": ["POST /api/auth/login", "POST /api/auth/register"]
      }
    }
  },
  "git_state": {
    "type": "object",
    "fields": {
      "branch": { "type": "string", "example": "impl/be/auth" },
      "commit_message": { "type": "string", "example": "[be_impl] auth: implement login, register, and logout endpoints" },
      "parent_branch": { "type": "string", "example": "impl/db/auth" }
    }
  }
}
```

### code_map.json (updated)
- **Path:** `code_map.json` (project root)
- **Format:** `json`
- **Consumers:** `pre_code_analysis` (future runs), `architecture_sync`, `fe_impl`
- **Shape:**
```json
{
  "modules": {
    "type": "object",
    "description": "Updated with BE layer entries",
    "example": {
      "auth": {
        "be": {
          "files": [
            {
              "path": "src/routes/auth.ts",
              "type": "route",
              "contract_ref": "openapi.json#/auth/login",
              "story_ref": "US-AUTH-001",
              "created_by": "be_impl",
              "action": "created"
            }
          ]
        }
      }
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `pre_code_analysis` | `pre_code_plan_be.json` (approved) | Implementation plan must be approved |
| input | `be_contract` | `openapi.json` | Contract defines all endpoints to implement |
| input | `be_policy` | `be_policy_flow.json` | Defines middleware chains per endpoint |
| input | `global_services` | `global_services_registry.json` | Shared services to import and use |
| input | `global_middleware` | `global_middleware_registry.json` | Middleware to wire into routes |
| input | `global_security` | `global_security_policies.json` | Security policies to enforce |
| input | `architect_reconcile` | `module_flow.json` | Cross-layer context |
| input | `db_test` | `report.json` (gate_status=pass) | DB tests must pass before BE begins — **conditional: only required if DB layer exists in this run; if no DB layer, BE starts after pre_code approval** |

| Blocks | Agent | Why |
|---|---|---|
| output | `be_test` | BE tests require implemented routes and services |
| output | `fe_impl` | FE implementation needs the API to be available |

---

## Orchestrator Communication

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

### Agent Identity

This agent's ID is `be_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: "be_impl", status: "completed")`
- **On failure:** `tracker_update(agent_id: "be_impl", status: "failed", add_intervention: { id: "...", agent_id: "be_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: "be_impl", fields: ["md.a"])
   -> { "md": { "a": ["auth"] } }
2. For each module in active list:
   a. node_read(agent_id: "be_impl", input_key: "pre_code_plan_be", unit_id: "auth")
   b. node_read(agent_id: "be_impl", input_key: "openapi", unit_id: "auth")
   c. Implement BE layer -> generate code files
   d. node_write(agent_id: "be_impl", output_key: "be_code", data: {...}, unit_id: "auth")
3. tracker_update(agent_id: "be_impl", status: "completed")
```

---

## Compressed Keymap

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

**be_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 (route/controller/service/middleware/model) |
| `fp.cr` | contract_ref | Contract reference |
| `fp.sr` | story_refs | Story references implemented |
| `fp.ei` | endpoints_implemented | Endpoints implemented in this file |
| `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 BE implementation output via registry-validated compressed keys. Agent calls `node_write(agent_id: "be_impl", output_key: "be_code", data: {...}, unit_id: "{module_id}")`. | Pending |
| `node_read` | Read upstream artifacts (pre_code_plan, openapi, be_policy_flow, global registries). Agent calls `node_read(agent_id: "be_impl", input_key: "openapi", unit_id: "{module_id}")`. | Pending |
| `tracker_read` | Read active modules. Agent calls `tracker_read(agent_id: "be_impl", fields: ["md.a"])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "be_impl", status: "completed")`. | Pending |
| `git_operations` | Branch creation, file staging, atomic commit | yes |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must implement ALL endpoints from openapi.json. Every path+method combination must have a corresponding route handler. |
| R-002 | `constraint` | `must` | Must wire middleware per be_policy_flow.json. Each endpoint's middleware_chain must be applied in the correct order. |
| R-003 | `constraint` | `must` | Must use shared services from global_services_registry. If a shared service exists for a function, use it — do not reimplement. |
| R-004 | `constraint` | `must` | Must follow global_security_policies. Protected endpoints must have auth middleware. RBAC must be enforced where specified. |
| R-005 | `not_allowed` | `must` | Must not duplicate middleware defined globally. Import from src/middleware/, do not recreate. |
| R-006 | `constraint` | `must` | Must only proceed if pre_code_plan_be.json has approved=true. |
| R-007 | `constraint` | `must` | Must commit atomically on impl/be/{module_id} branch. |
| R-008 | `output_quality` | `must` | Must update code_map.json with entries for every file created or modified. |
| R-009 | `output_quality` | `should` | Route handlers should delegate to service functions — no direct DB access from routes. |
| R-010 | `output_quality` | `should` | Error responses should follow a consistent format defined in the OpenAPI components section. |
| R-011 | `data_handling` | `should` | Request validation should match OpenAPI request body schemas. |
| R-012 | `scope_boundary` | `must` | Must not implement UI or database schema changes. BE layer only. |
| 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: "be_impl", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "be_impl", status: "failed", add_intervention: {...})` before exiting on failure. |
| R-016 | `constraint` | `must` | Must read active modules via `tracker_read(agent_id: "be_impl", fields: ["md.a"])` and process only active modules. Must not hardcode module lists. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32768 |
| max_endpoints_per_module | 50 |
| timeout_seconds | 600 |

---

## Scope Boundary

**In scope:**
- Generating API route handlers from OpenAPI spec
- Generating service functions for business logic
- Wiring middleware per policy flow
- Importing and using shared services from global registry
- Applying security policies (auth, RBAC)
- Request validation matching OpenAPI schemas
- Error handling with consistent response formats
- Updating code_map.json with BE layer entries
- Creating git branch and atomic commit
- In fixation mode: reading test report, targeting only failing tests, applying minimal fixes without full regeneration

**Out of scope:**
- Modifying database schema or migrations (db_impl does this)
- Implementing UI components (fe_impl does this)
- Running tests (be_test does this)
- Creating new middleware (those come from global_middleware)
- Making API design decisions (those come from openapi.json)
- Implementing external integrations (uses stubs from global_integrations)

---

## Triggers

- Orchestrator activates this agent when pre_code_plan_be.json has approved=true AND (db_test report.json has gate_status=pass OR DB layer is absent from this run)
- Module order follows module_priority_sequence.json
- In retrofit mode, triggered only for modules with BE layer changes
- In fixation mode (inner retry loop), re-triggered by orchestrator when be_test fails and retry count < 3 — receives test_output/{module_id}/be/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 BE layer
- In bugfix pipeline, triggered with diagnosis.json context and fix_plan targeting only diagnosed BE issues

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | Approved pre_code_plan_be.json loaded, DB test gate confirmed pass | `log` |
| `CP-002` | OpenAPI spec and policy flow loaded | `log` |
| `CP-003` | Global services and middleware registries loaded | `log` |
| `CP-004` | Route handlers generated for all endpoints | `log` |
| `CP-005` | Service functions generated | `log` |
| `CP-006` | Middleware wired per policy flow | `log` |
| `CP-007` | Security policies applied to protected endpoints | `log` |
| `CP-008` | code_map.json updated with BE entries | `log` |
| `CP-009` | Git branch created and atomic commit made | `notify` — BE implementation complete, be_test can proceed |

---

## Validation Criteria

- Every endpoint in openapi.json has a corresponding route handler
- Every route has the correct middleware chain as defined in be_policy_flow.json
- No middleware is duplicated that exists in global_middleware_registry
- Protected endpoints have auth middleware applied
- All route handlers delegate to service functions (no direct DB calls in routes)
- Git commit exists on impl/be/{module_id} branch
- code_map.json has entries for every file created or modified
- Commit message follows the [be_impl] convention
- Request/response shapes match OpenAPI schemas

---

## Context Sources

- pre_code_plan_be.json (approved implementation plan)
- openapi.json (endpoint definitions)
- be_policy_flow.json (middleware chains)
- global_services_registry.json (shared services)
- global_middleware_registry.json (middleware definitions)
- global_security_policies.json (security requirements)
- module_flow.json (cross-layer context)
- DB implementation files (for Prisma client imports)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if BE implementation fails, 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` | Route generator that produces Express/Fastify route handlers from OpenAPI path+operation definitions with correct HTTP methods, request parsing, and response formatting | this agent | Manual route writing is error-prone and risks missing endpoints or incorrect response codes |
| `TG-006` | Middleware wirer that reads be_policy_flow and generates the correct middleware chain import and application for each route | this agent | Manual middleware wiring risks incorrect ordering or missing middleware |
| `TG-007` | OpenAPI sync checker that validates implemented routes match the spec (paths, methods, request/response schemas) | this agent | Contract drift would go undetected until testing |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `be-impl` |
| `agentName` | ready | `be_impl` |
| `agentRole` | ready | "Backend API Route and Service Generator" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | 8 inputs: pre_code_plan, openapi, be_policy_flow, global_services, global_middleware, global_security, module_flow, db_test gate |
| `guardrails` | ready | 16 rules defined across constraint, not_allowed, output_quality, data_handling, scope_boundary categories |
| `scopeBoundary` | ready | 9 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | TypeScript route/service/middleware files, code_map updates |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 9 checkpoints with actions |
| `validation` | ready | 9 validation criteria |
| `contextSources` | ready | 8 context sources |
| `metadata` | ready | phase: "10", mode: "all", granularity: "per_module" |
