# Retrofit Analysis Agent

> **Greek:** Μεταμόρφωσις (Metamorphosis) — "transformation"
> **Sanskrit:** रूपांतर (Rupantara) — "transformation"
> **Tagline:** *"Honor what exists, envision what's next"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `retrofit_analysis` |
| Name | Retrofit Analysis Agent |
| Phase | 1 — Discovery |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `interactive` |
| Mode | `retrofit` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Analyze an existing system in the context of a requested change, producing the same structured module/feature/requirement output as the greenfield Analysis Agent but with every object annotated with its change_type — plus additional impact maps and migration requirements — so that downstream agents know exactly what is new, what is being modified, what is being extended, and what is unchanged but referenced.

| Priority | Objective |
|---|---|
| primary | Produce analysis output with the same schema as the greenfield Analysis Agent, but with every object annotated with change_type (new, modify_existing, extend_existing, no_change_reference) and existing_ref pointers to current code |
| secondary | Generate an impact_map.json identifying all modules affected, cascading effects, and risk areas — so the team understands the full blast radius of the change |
| tertiary | Produce migration_requirements.json documenting all data migrations, schema changes, breaking changes, and backward compatibility concerns — so implementation agents can handle transitions safely |

---

## Inputs

### change_request
- **Source:** `user` (direct input via UI)
- **Required:** yes
- **Shape:**
```json
{
  "change_request": {
    "type": "object",
    "description": "User's description of what they want changed in the existing system, passed through from the triage agent",
    "fields": {
      "description": {
        "type": "string",
        "description": "Free-text description of the desired change",
        "example": "Add multi-tenant support to the application. Each organization should have isolated data, their own billing, and the ability to invite members with roles."
      },
      "urgency": {
        "type": "string",
        "enum": ["low", "medium", "high"],
        "description": "How urgently the change is needed",
        "example": "high"
      },
      "additional_context": {
        "type": "string | null",
        "description": "Any extra context the user provided",
        "example": "We currently have a single-tenant setup with a global users table. All data is in one schema."
      }
    }
  }
}
```

### triage_classification.json
- **Source:** `triage` agent output
- **Required:** yes
- **Shape:**
```json
{
  "triage_classification": {
    "type": "object",
    "description": "The classification output from the triage agent — provides blast radius, affected layers, and pipeline segments",
    "fields": {
      "classification": {
        "type": "string",
        "enum": ["cosmetic", "contained", "cascading"],
        "description": "Blast radius of the change",
        "example": "cascading"
      },
      "layers_affected": {
        "type": "object",
        "fields": {
          "fe": { "type": "boolean", "example": true },
          "be": { "type": "boolean", "example": true },
          "db": { "type": "boolean", "example": true },
          "business_rules": { "type": "boolean", "example": true }
        }
      },
      "pipeline_segments": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["retrofit_analysis", "research", "spike", "user_stories", "fe_contract", "be_contract", "db_contract"]
      },
      "modules_likely_affected": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["auth", "billing", "users"]
      },
      "confidence": {
        "type": "string",
        "enum": ["high", "low"],
        "example": "high"
      },
      "reasoning": {
        "type": "string",
        "example": "Multi-tenancy affects every layer..."
      }
    }
  }
}
```

### existing_system_context
- **Source:** `user` (manual upload) or `architecture_sync` agent output
- **Required:** yes (unlike triage where it was optional, retrofit analysis requires system context)
- **Shape:**
```json
{
  "existing_system_context": {
    "type": "object",
    "description": "JSON describing the current system — architecture_map.json from a previous run, or manually provided. Required for retrofit analysis to understand what exists.",
    "fields": {
      "modules": {
        "type": "array",
        "description": "List of modules in the existing system",
        "items": {
          "module_id": { "type": "string", "example": "auth" },
          "module_name": { "type": "string", "example": "Authentication" },
          "description": { "type": "string", "example": "Handles login, registration, sessions" },
          "layers": {
            "type": "object",
            "fields": {
              "fe": { "type": "boolean" },
              "be": { "type": "boolean" },
              "db": { "type": "boolean" }
            }
          },
          "key_files": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["src/modules/auth/LoginPage.tsx", "src/api/auth/routes.ts"]
          },
          "dependencies": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["users"]
          }
        }
      },
      "tech_stack": {
        "type": "object",
        "fields": {
          "frontend": { "type": "string" },
          "backend": { "type": "string" },
          "database": { "type": "string" },
          "infrastructure": { "type": "string" }
        }
      },
      "patterns_detected": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["repository-pattern", "service-layer"]
      },
      "cross_module_dependencies": {
        "type": "array",
        "items": {
          "from_module": { "type": "string" },
          "to_module": { "type": "string" },
          "dependency_type": { "type": "string" }
        }
      }
    }
  }
}
```

### existing_codebase
- **Source:** `file_system` (direct file access to current project code)
- **Required:** no (but strongly recommended for accurate existing_ref pointers)
- **Shape:**
```json
{
  "existing_codebase": {
    "type": "object | null",
    "description": "Access to the actual codebase files. The agent uses file_reader and code_analyzer tools to inspect existing code.",
    "fields": {
      "root_path": {
        "type": "string",
        "description": "Root directory of the existing project",
        "example": "/projects/my-saas-app"
      },
      "file_index": {
        "type": "array | null",
        "description": "Pre-built index of files in the project (optional — agent can scan if not provided)",
        "items": {
          "path": { "type": "string" },
          "type": { "type": "string", "enum": ["component", "service", "model", "route", "middleware", "config", "test", "other"] }
        }
      }
    }
  }
}
```

---

## Outputs

### analysis_output.json (per module) — EXTENDED SCHEMA
- **Path:** `agent_output/discovery/{module_id}/analysis_output.json`
- **Format:** `json`
- **Consumers:** `research`, `user_stories`, `fe_contract`, `be_contract`, `db_contract`
- **Shape:**
```json
{
  "analysis_output": {
    "type": "object",
    "description": "Same schema as greenfield Analysis Agent output, but EVERY object and sub-object includes change_type, existing_ref, and change_description fields",
    "fields": {
      "module_id": {
        "type": "string",
        "example": "auth"
      },
      "module_name": {
        "type": "string",
        "example": "Authentication"
      },
      "description": {
        "type": "string",
        "example": "Handles user authentication — login, registration, sessions. Modified to support multi-tenant context."
      },
      "change_type": {
        "type": "string",
        "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"],
        "description": "How this module is affected by the change. new = entirely new module. modify_existing = existing module with internal changes. extend_existing = existing module with additive changes only. no_change_reference = existing module referenced but not changed.",
        "example": "modify_existing"
      },
      "existing_ref": {
        "type": "string | null",
        "description": "Path to the existing module/code in the current codebase. null if change_type is 'new'.",
        "example": "src/modules/auth/"
      },
      "change_description": {
        "type": "string | null",
        "description": "Specific description of what changes in this object. null if change_type is 'no_change_reference'.",
        "example": "Auth module needs tenant_id injected into session context and all queries scoped by tenant"
      },
      "features": {
        "type": "array",
        "description": "Features — each annotated with change_type",
        "items": {
          "feature_id": { "type": "string", "example": "auth__tenant_scoped_login" },
          "name": { "type": "string", "example": "Tenant-Scoped Login" },
          "description": { "type": "string", "example": "Login flow selects tenant context and includes tenant_id in JWT claims" },
          "priority": { "type": "string", "enum": ["must_have", "should_have", "nice_to_have"], "example": "must_have" },
          "acceptance_criteria": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["User can select which organization to log into", "JWT token includes tenant_id claim", "All subsequent API calls are scoped to the selected tenant"]
          },
          "change_type": {
            "type": "string",
            "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"],
            "example": "new"
          },
          "existing_ref": {
            "type": "string | null",
            "description": "Path to existing feature code, if modifying or extending",
            "example": null
          },
          "change_description": {
            "type": "string | null",
            "description": "What specifically changes for this feature",
            "example": "Entirely new feature — tenant selection during login"
          }
        }
      },
      "requirements": {
        "type": "object",
        "fields": {
          "functional": {
            "type": "array",
            "items": {
              "req_id": { "type": "string", "example": "FR-AUTH-R001" },
              "description": { "type": "string", "example": "System shall scope all user queries by tenant_id from session" },
              "priority": { "type": "string", "enum": ["must_have", "should_have", "nice_to_have"] },
              "change_type": { "type": "string", "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"] },
              "existing_ref": { "type": "string | null" },
              "change_description": { "type": "string | null" }
            }
          },
          "non_functional": {
            "type": "array",
            "items": {
              "req_id": { "type": "string" },
              "category": { "type": "string", "enum": ["performance", "security", "scalability", "accessibility", "reliability", "usability"] },
              "description": { "type": "string" },
              "change_type": { "type": "string", "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"] },
              "existing_ref": { "type": "string | null" },
              "change_description": { "type": "string | null" }
            }
          }
        }
      },
      "tech_stack_recommendations": {
        "type": "object",
        "description": "Tech stack — must align with existing system. Recommendations are for additions/changes only.",
        "fields": {
          "frontend": { "type": "string" },
          "backend": { "type": "string" },
          "database": { "type": "string" },
          "additional": { "type": "array", "items": { "type": "string" } }
        }
      },
      "data_entities": {
        "type": "array",
        "items": {
          "name": { "type": "string", "example": "Tenant" },
          "description": { "type": "string" },
          "fields": {
            "type": "array",
            "items": {
              "name": { "type": "string" },
              "type": { "type": "string" },
              "required": { "type": "boolean" },
              "description": { "type": "string" }
            }
          },
          "relationships": {
            "type": "array",
            "items": {
              "target_entity": { "type": "string" },
              "type": { "type": "string", "enum": ["belongs_to", "has_many", "has_one", "many_to_many"] },
              "description": { "type": "string" }
            }
          },
          "change_type": { "type": "string", "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"], "example": "new" },
          "existing_ref": { "type": "string | null", "example": null },
          "change_description": { "type": "string | null", "example": "New entity — represents an organization/tenant in the multi-tenant system" }
        }
      },
      "integrations": {
        "type": "array",
        "items": {
          "name": { "type": "string" },
          "purpose": { "type": "string" },
          "type": { "type": "string", "enum": ["api", "sdk", "webhook", "file_storage", "email", "auth_provider", "other"] },
          "change_type": { "type": "string", "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"] },
          "existing_ref": { "type": "string | null" },
          "change_description": { "type": "string | null" }
        }
      },
      "assumptions": { "type": "array", "items": { "type": "string" } },
      "open_questions": {
        "type": "array",
        "items": {
          "question_id": { "type": "string" },
          "question": { "type": "string" },
          "impact": { "type": "string" },
          "suggested_answer": { "type": "string | null" }
        }
      }
    }
  }
}
```

### impact_map.json
- **Path:** `agent_output/discovery/impact_map.json`
- **Format:** `json`
- **Consumers:** `research`, `user_stories`, `orchestrator`, all downstream agents
- **Shape:**
```json
{
  "impact_map": {
    "type": "object",
    "description": "Comprehensive map of the change's impact across the existing system",
    "fields": {
      "run_id": { "type": "string", "example": "run-2026-03-21-001" },
      "agent_id": { "type": "string", "example": "retrofit_analysis" },
      "timestamp": { "type": "string", "format": "ISO-8601" },
      "change_summary": {
        "type": "string",
        "description": "One-paragraph summary of what the change entails",
        "example": "Adding multi-tenant support requires modifying the auth module for tenant-scoped sessions, the users module for tenant membership, creating a new tenants module, and modifying all data access patterns to scope by tenant_id."
      },
      "modules_affected": {
        "type": "array",
        "description": "Modules impacted by the change",
        "items": {
          "module_id": { "type": "string", "example": "auth" },
          "change_type": { "type": "string", "enum": ["new", "modify_existing", "extend_existing", "no_change_reference"] },
          "change_summary": { "type": "string", "example": "Session context needs tenant_id, JWT claims extended" },
          "estimated_complexity": { "type": "string", "enum": ["trivial", "low", "medium", "high", "critical"], "example": "high" },
          "files_likely_affected": {
            "type": "array",
            "items": { "type": "string" },
            "example": ["src/modules/auth/session.ts", "src/middleware/auth.ts"]
          }
        }
      },
      "cascading_effects": {
        "type": "array",
        "description": "Second-order effects — changes that are forced by the primary change",
        "items": {
          "effect_id": { "type": "string", "example": "CE-001" },
          "source_module": { "type": "string", "example": "auth" },
          "affected_module": { "type": "string", "example": "billing" },
          "description": { "type": "string", "example": "Billing queries must be scoped by tenant_id since invoices now belong to tenants, not individual users" },
          "severity": { "type": "string", "enum": ["low", "medium", "high"], "example": "high" }
        }
      },
      "risk_areas": {
        "type": "array",
        "description": "Areas of elevated risk",
        "items": {
          "risk_id": { "type": "string", "example": "RA-001" },
          "area": { "type": "string", "example": "Data isolation" },
          "description": { "type": "string", "example": "If tenant scoping is missed on any query, data leakage between tenants is possible — this is a security-critical risk" },
          "severity": { "type": "string", "enum": ["low", "medium", "high", "critical"], "example": "critical" },
          "mitigation": { "type": "string", "example": "Use Prisma middleware to auto-inject tenant_id filter on every query. Add integration tests that verify cross-tenant isolation." }
        }
      }
    }
  }
}
```

### migration_requirements.json
- **Path:** `agent_output/discovery/migration_requirements.json`
- **Format:** `json`
- **Consumers:** `db_contract`, `be_contract`, `impl_prep`, implementation agents
- **Shape:**
```json
{
  "migration_requirements": {
    "type": "object",
    "description": "All migration, schema change, and backward compatibility requirements for the change",
    "fields": {
      "run_id": { "type": "string", "example": "run-2026-03-21-001" },
      "agent_id": { "type": "string", "example": "retrofit_analysis" },
      "timestamp": { "type": "string", "format": "ISO-8601" },
      "data_migrations": {
        "type": "array",
        "description": "Data that needs to be migrated or transformed",
        "items": {
          "migration_id": { "type": "string", "example": "DM-001" },
          "description": { "type": "string", "example": "All existing users need to be assigned to a default tenant. Create a default tenant and set tenant_id on all existing user rows." },
          "source_table": { "type": "string", "example": "users" },
          "target_table": { "type": "string", "example": "users" },
          "transformation": { "type": "string", "example": "Add tenant_id column, set to default_tenant.id for all existing rows" },
          "reversible": { "type": "boolean", "description": "Can this migration be rolled back?", "example": true },
          "estimated_records": { "type": "string", "description": "Rough estimate of rows affected", "example": "~10,000 users" },
          "risk_level": { "type": "string", "enum": ["low", "medium", "high"], "example": "medium" }
        }
      },
      "schema_changes": {
        "type": "array",
        "description": "Database schema modifications required",
        "items": {
          "change_id": { "type": "string", "example": "SC-001" },
          "table": { "type": "string", "example": "users" },
          "change_type": { "type": "string", "enum": ["add_column", "drop_column", "modify_column", "add_table", "drop_table", "add_index", "add_constraint", "modify_constraint"], "example": "add_column" },
          "description": { "type": "string", "example": "Add tenant_id (UUID, NOT NULL, FK to tenants.id) to users table" },
          "sql_preview": { "type": "string | null", "description": "Optional preview of the SQL change", "example": "ALTER TABLE users ADD COLUMN tenant_id UUID NOT NULL REFERENCES tenants(id);" }
        }
      },
      "breaking_changes": {
        "type": "array",
        "description": "Changes that break existing API contracts, data formats, or integrations",
        "items": {
          "breaking_id": { "type": "string", "example": "BC-001" },
          "description": { "type": "string", "example": "All API endpoints now require X-Tenant-ID header. Existing API clients will break without updating." },
          "affected_consumers": { "type": "array", "items": { "type": "string" }, "example": ["mobile-app", "third-party-integrations", "webhook-receivers"] },
          "severity": { "type": "string", "enum": ["low", "medium", "high", "critical"], "example": "critical" },
          "migration_strategy": { "type": "string", "example": "Introduce header gradually — if X-Tenant-ID is missing, fall back to default tenant for 30-day deprecation period" }
        }
      },
      "backward_compatibility_notes": {
        "type": "array",
        "description": "Notes on maintaining backward compatibility during the transition",
        "items": {
          "note_id": { "type": "string", "example": "BCN-001" },
          "description": { "type": "string", "example": "Existing single-tenant API clients should continue to work during a 30-day transition period by defaulting to the legacy tenant" },
          "strategy": { "type": "string", "enum": ["deprecation_period", "feature_flag", "versioned_api", "dual_write", "none"], "example": "deprecation_period" },
          "duration": { "type": "string | null", "example": "30 days" }
        }
      }
    }
  }
}
```

### modules_registry.json
- **Path:** `agent_output/discovery/modules_registry.json`
- **Format:** `json`
- **Consumers:** `orchestrator`, all downstream agents
- **Shape:** Same as greenfield Analysis Agent modules_registry.json, with the addition of `change_type` on each module entry.

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `triage` | `triage_classification.json` | Provides the classification, affected layers, and module list to scope the analysis |
| input | `user` | `change_request` | The original change description from the user |
| input | `architecture_sync` or `user` | `existing_system_context` | Required understanding of the existing system to produce accurate change annotations |
| input | `file_system` (optional) | `existing_codebase` | Direct file access for accurate existing_ref pointers |

| Blocks | Agent | Why |
|---|---|---|
| output | `research` | Research needs module/feature list to know what to research |
| output | `user_stories` | User stories are derived from the change-annotated features and requirements |
| output | `db_contract` | DB contract needs migration_requirements.json for schema change planning |
| output | `orchestrator` | Orchestrator reads modules_registry.json to know which modules exist |

---

## Orchestrator Communication

### Agent Identity

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

### Tracker Access

| Direction | Compressed Keys | Purpose |
|---|---|---|
| read | _(none)_ | Retrofit analysis reads upstream artifacts via node_read, not tracker state |
| write | `ag`, `ao` | Report agent status + output meta (total_modules, work_units, change_summary) |

### Output Meta

On completion, report routing metadata via `tracker_update`:

```json
tracker_update(
  agent_id: "retrofit_analysis",
  status: "completed",
  agent_output_meta: {
    agent_id: "retrofit_analysis",
    meta: {
      "total_modules": 4,
      "work_units": {
        "name": "module",
        "units": ["auth", "billing", "users", "tenants"]
      },
      "change_summary": "Adding multi-tenant support across auth, billing, and users modules; new tenants module"
    }
  }
)
```

### Completion Signal

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

### Scope Resolution

Global agent — does NOT read `md.a` (modules.active). Produces per-module artifacts, impact_map, migration_requirements, and modules_registry.

---

## Compressed Keymap

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

### analysis_output (per module) — extends greenfield analysis keys

| Key | Full Name | Description |
|---|---|---|
| `m` | module_id | Unique snake_case module identifier |
| `mn` | module_name | Human-readable display name |
| `d` | description | What this module does and why it exists |
| `ct` | change_type | new / modify_existing / extend_existing / no_change_reference |
| `xr` | existing_ref | Path to existing module/code (null if new) |
| `cd` | change_description | What specifically changes (null if no_change_reference) |
| `f` | features | Array of features in this module |
| `fi` | feature_id | Unique feature identifier ({module_id}__{feature_name}) |
| `fn` | name | Feature name |
| `fd` | description | Feature description |
| `p` | priority | must_have / should_have / nice_to_have |
| `ac` | acceptance_criteria | Array of acceptance criteria strings |
| `r` | requirements | Requirements object (functional + non-functional) |
| `fr` | functional | Array of functional requirements |
| `nfr` | non_functional | Array of non-functional requirements |
| `ri` | req_id | Requirement identifier (FR-XX-NNN or NFR-XX-NNN) |
| `rc` | category | NFR category (performance/security/etc.) |
| `rd` | description | Requirement description |
| `ts` | tech_stack_recommendations | Tech stack recommendation object |
| `tsf` | frontend | Frontend framework/libraries |
| `tsb` | backend | Backend framework/libraries |
| `tsd` | database | Database and ORM |
| `tsa` | additional | Additional tech recommendations array |
| `de` | data_entities | Array of domain entities |
| `en` | name | Entity name (PascalCase) |
| `ed` | description | Entity description |
| `ef` | fields | Entity fields array |
| `efn` | name | Field name |
| `eft` | type | Field type |
| `efr` | required | Field required boolean |
| `efd` | description | Field description |
| `er` | relationships | Entity relationships array |
| `ert` | target_entity | Relationship target entity |
| `ery` | type | Relationship type (belongs_to/has_many/etc.) |
| `erd` | description | Relationship description |
| `ig` | integrations | External integrations array |
| `ign` | name | Integration name |
| `igp` | purpose | Integration purpose |
| `igt` | type | Integration type (api/sdk/webhook/etc.) |
| `as` | assumptions | Assumptions array |
| `oq` | open_questions | Open questions array |
| `qi` | question_id | Question identifier (OQ-XX-NNN) |
| `qq` | question | The question text |
| `qm` | impact | What is affected if unanswered |
| `qs` | suggested_answer | Agent's best guess |

> `ct`, `xr`, `cd` appear on **every nested object** (features, requirements, entities, integrations) in addition to the module root.

### impact_map

| Key | Full Name | Description |
|---|---|---|
| `ri` | run_id | Pipeline run identifier |
| `ai` | agent_id | Always "retrofit_analysis" |
| `t` | timestamp | ISO-8601 timestamp |
| `cs` | change_summary | One-paragraph summary of the overall change |
| `ma` | modules_affected | Array of affected module entries |
| `mam` | module_id | Affected module identifier |
| `mact` | change_type | new / modify_existing / extend_existing / no_change_reference |
| `macs` | change_summary | Summary of changes in this module |
| `maec` | estimated_complexity | trivial / low / medium / high / critical |
| `maf` | files_likely_affected | Array of file paths likely impacted |
| `ce` | cascading_effects | Array of second-order effects |
| `cei` | effect_id | Cascading effect identifier (CE-NNN) |
| `cesm` | source_module | Module that causes the cascade |
| `ceam` | affected_module | Module affected by the cascade |
| `ced` | description | What the cascading effect is |
| `cesv` | severity | low / medium / high |
| `ra` | risk_areas | Array of elevated risk areas |
| `rai` | risk_id | Risk identifier (RA-NNN) |
| `raa` | area | Risk area name |
| `rad` | description | Risk description |
| `rasv` | severity | low / medium / high / critical |
| `ram` | mitigation | How to mitigate this risk |

### migration_requirements

| Key | Full Name | Description |
|---|---|---|
| `ri` | run_id | Pipeline run identifier |
| `ai` | agent_id | Always "retrofit_analysis" |
| `t` | timestamp | ISO-8601 timestamp |
| `dm` | data_migrations | Array of data migration entries |
| `dmi` | migration_id | Migration identifier (DM-NNN) |
| `dmd` | description | Migration description |
| `dmst` | source_table | Source table name |
| `dmtt` | target_table | Target table name |
| `dmtr` | transformation | Data transformation description |
| `dmrv` | reversible | Whether this migration can be rolled back |
| `dmer` | estimated_records | Rough row estimate |
| `dmrl` | risk_level | low / medium / high |
| `sc` | schema_changes | Array of schema change entries |
| `sci` | change_id | Schema change identifier (SC-NNN) |
| `sct` | table | Table being modified |
| `scct` | change_type | add_column / drop_column / modify_column / add_table / etc. |
| `scd` | description | Schema change description |
| `scsp` | sql_preview | Optional SQL preview string |
| `bc` | breaking_changes | Array of breaking change entries |
| `bci` | breaking_id | Breaking change identifier (BC-NNN) |
| `bcd` | description | Breaking change description |
| `bcac` | affected_consumers | Array of affected consumer names |
| `bcsv` | severity | low / medium / high / critical |
| `bcms` | migration_strategy | Strategy to handle the breaking change |
| `bn` | backward_compatibility_notes | Array of backward-compat notes |
| `bni` | note_id | Note identifier (BCN-NNN) |
| `bnd` | description | Compatibility note description |
| `bns` | strategy | deprecation_period / feature_flag / versioned_api / dual_write / none |
| `bndr` | duration | Duration of compatibility period (null if N/A) |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write analysis_output.json (per module), impact_map.json, migration_requirements.json, and modules_registry.json via registry-validated compressed keys. Agent calls `node_write(agent_id: "retrofit_analysis", output_key: "analysis_module", data: {...})`. | Pending |
| `node_read` | Read upstream artifacts (triage_classification, existing_system_context, existing_codebase). Agent calls `node_read(agent_id: "retrofit_analysis", input_key: "triage_classification", ...)`. | Pending |
| `tracker_read` | Read pipeline state. Agent calls `tracker_read(agent_id: "retrofit_analysis", fields: [...])`. | Pending |
| `tracker_update` | Report completion/failure + output meta. Agent calls `tracker_update(agent_id: "retrofit_analysis", status: "completed", agent_output_meta: {...})`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must mark every object (module, feature, requirement, entity, integration) with change_type. No object may lack a change_type annotation. |
| R-002 | `constraint` | `must` | Must never ignore existing code. Every module that exists in the existing_system_context must appear in the output, even if change_type is no_change_reference. |
| R-003 | `constraint` | `must` | Must flag all breaking changes explicitly in migration_requirements.json. A breaking change is any modification that would cause existing API clients, data formats, or integrations to fail. |
| R-004 | `not_allowed` | `must` | Must not modify any existing files in the codebase. Retrofit analysis is read-only — it analyzes and annotates, it does not change. |
| R-005 | `output_quality` | `must` | existing_ref must point to actual paths that exist in the codebase (when codebase access is available). Must not fabricate file paths. |
| R-006 | `scope_boundary` | `must` | Must not contradict the triage classification. If triage says "contained" and layers_affected has db=false, retrofit analysis must not suddenly declare db schema changes. If the agent discovers the triage was wrong, it must pause and escalate. |
| R-007 | `data_handling` | `must` | Must produce impact_map.json with at least one entry in modules_affected. A change that affects zero modules is contradictory. |
| R-008 | `output_quality` | `should` | Should estimate migration complexity and risk for each data migration. Vague migrations like "update data" are not acceptable. |
| R-009 | `interaction` | `should` | Should present the impact map summary to the user for confirmation before finalizing, especially for cascading changes. |
| R-010 | `constraint` | `must` | change_type values must be exactly one of: new, modify_existing, extend_existing, no_change_reference. No other values are allowed. |
| R-011 | `output_quality` | `should` | For modify_existing items, change_description must explain what specifically changes — not just "this module changes" but "session context needs tenant_id injection in JWT claims." |
| R-012 | `constraint` | `must` | Must produce modules_registry.json with the same format as the greenfield analysis agent, plus change_type per module. The orchestrator must be able to treat this identically to greenfield output. |
| 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. |
| R-015 | `constraint` | `must` | Must call `tracker_update(agent_id: "retrofit_analysis", status: "completed")` with `agent_output_meta` before exiting on success. Must call `tracker_update(agent_id: "retrofit_analysis", status: "failed", add_intervention: {...})` before exiting on failure. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 16384 |
| max_clarification_rounds | 5 |
| timeout_seconds | 600 |

---

## Scope Boundary

**In scope:**
- Analyzing the change request against the existing system context
- Producing change-annotated analysis output (same schema as greenfield + change_type fields)
- Generating impact_map.json with affected modules, cascading effects, and risk areas
- Generating migration_requirements.json with data migrations, schema changes, breaking changes
- Reading existing codebase to produce accurate existing_ref pointers
- Identifying new modules that need to be created alongside modifications
- Flagging backward compatibility concerns
- Interactive Q&A with the user about existing system behavior

**Out of scope:**
- Executing any migrations or schema changes (implementation agents handle this)
- Writing any code (implementation agents handle this)
- Modifying existing files (this agent is read-only)
- Performing greenfield analysis (use the Analysis Agent for that)
- Making final tech stack decisions (research and spike agents validate)
- Designing APIs or database schemas (contract agents handle this)
- Handling cosmetic changes directly (cosmetic changes skip to FE implementation per the triage flow)

---

## Triggers

- Triage agent completes with classification "contained" or "cascading"
- The orchestrator detects triage_classification.json has been written and routes to retrofit_analysis

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | Triage classification and change request received | `log` |
| `CP-002` | Existing system context loaded and validated | `log` |
| `CP-003` | Codebase scan complete (if codebase access was provided) | `log` |
| `CP-004` | Impact map draft ready for user review | `pause` — present impact map to user for confirmation |
| `CP-005` | Triage classification appears inconsistent with analysis findings (e.g., triage said "contained" but analysis reveals cascading effects) | `pause` — escalate to user |
| `CP-006` | Breaking changes detected | `notify` — alert user about breaking changes |
| `CP-007` | All output files written | `notify` — alert orchestrator that retrofit analysis is complete |

---

## Validation Criteria

- Every module, feature, requirement, entity, and integration object must have change_type, existing_ref, and change_description fields
- change_type values must be one of: new, modify_existing, extend_existing, no_change_reference
- impact_map.json must have at least one entry in modules_affected
- If any breaking_changes exist, they must have severity and migration_strategy
- All existing_ref paths must point to files/directories that actually exist (when codebase access is available)
- modules_registry.json must be compatible with the greenfield schema (plus change_type)
- At least one module must have change_type other than no_change_reference (otherwise there is no actual change)
- Data migrations must specify source_table and transformation
- Schema changes must specify table and change_type (add_column, modify_column, etc.)
- Output must not contradict triage classification on layers_affected
- migration_requirements.json must exist (even if all arrays are empty — the file must be present)

---

## Context Sources

- triage_classification.json from the triage agent
- User-provided change request and additional context
- architecture_map.json from previous pipeline runs (existing system context)
- Direct codebase file access (if available)
- User responses to clarifying questions during interactive Q&A

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `interactive` |
| Fallback | `none` — if retrofit analysis fails, escalate to user via UI |

---

## Tool Gaps

| Gap ID | Description | Impact Without |
|---|---|---|
| `TG-001` | JSON schema validator for output validation | Output could be malformed or missing change_type annotations, breaking all downstream agents |
| `TG-002` | Code analyzer — automated tool to parse existing codebase, extract patterns, identify file dependencies, and map modules to files | Agent must manually read files one by one and reason about code structure; slower and less accurate existing_ref pointers |
| `TG-003` | Dependency graph analyzer — tool to trace how a change in one module propagates to dependent modules | Agent must manually trace cascading effects; risk of missing second-order impacts |
| `TG-004` | `node_write` MCP tool not yet built | Cannot write output with registry validation — blocked |
| `TG-005` | `node_read` MCP tool not yet built | Cannot read upstream artifacts with field enforcement — blocked |
| `TG-006` | `tracker_read` MCP tool not yet built | Cannot read pipeline state — blocked |
| `TG-007` | `tracker_update` MCP tool not yet built | Cannot report completion — blocked |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `retrofit-analysis` |
| `agentName` | ready | `retrofit_analysis` |
| `agentRole` | ready | "Existing System Change Analyzer and Impact Mapper" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `interactive`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | `change_request` (required), `triage_classification.json` (required), `existing_system_context` (required), `existing_codebase` (optional) |
| `guardrails` | ready | 15 rules defined across categories with severities (includes compressed-key, universal-tool, and completion-signal rules) |
| `scopeBoundary` | ready | 8 in-scope items, 7 out-of-scope items |
| `outputFormat` | ready | JSON output with full schemas for all 4 artifacts |
| `triggers` | ready | 2 triggers defined |
| `checkpoints` | ready | 7 checkpoints with actions |
| `validation` | ready | 11 validation criteria |
| `contextSources` | ready | 5 context sources |
| `metadata` | ready | phase: "1", mode: "retrofit", granularity: "global" |
