# Unified Contract Reconcile Agent

> **Greek:** Ἁρμονία (Harmonía) — "harmony/union"
> **Sanskrit:** ऐक्य (Aikya) — "unity/oneness"
> **Tagline:** *"Three contracts, one truth"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `unified_reconcile` |
| Name | Unified Contract Reconcile Agent |
| Phase | 5 — Contracts & Wireframes |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Process unified review findings by applying cross-layer fixes to FE, BE, and DB contract files — maintaining referential integrity when patching across layers, cascading changes appropriately, and deciding whether to loop back to review, proceed to Phase 6 (Normalize), or escalate unresolvable conflicts to the user.

| Priority | Objective |
|---|---|
| primary | Apply cross-layer fixes that maintain referential integrity — when a field name is corrected in one layer, cascade the correction to all layers that reference it |
| secondary | Never break existing valid cross-references while fixing identified issues — patches must preserve working relationships between layers |
| tertiary | Produce clear reconcile results with quality scoring across all three layers so the pipeline and user understand the contracts' readiness for Phase 6 |

---

## Inputs

### unified_review_output.json
- **Source:** `unified_review` agent -> `agent_output/reviews/unified_review_output.json`
- **Required:** yes
- **Shape:**
```json
{
  "review_id": {
    "type": "string",
    "example": "UNI-REV-2026-03-21-001"
  },
  "modules_reviewed": {
    "type": "array",
    "items": { "type": "string" }
  },
  "findings": {
    "type": "array",
    "items": {
      "finding_id": {
        "type": "string",
        "example": "UNI-F-001"
      },
      "category": {
        "type": "string",
        "enum": ["fe_be_mismatch", "be_db_mismatch", "cross_module_inconsistency", "naming_violation", "missing_error_handling", "security_gap"]
      },
      "severity": {
        "type": "string",
        "enum": ["critical", "major", "minor", "info"]
      },
      "layers_affected": {
        "type": "array",
        "items": { "type": "string", "enum": ["fe", "be", "db"] }
      },
      "affected_modules": {
        "type": "array",
        "items": { "type": "string" }
      },
      "description": { "type": "string" },
      "suggestion": { "type": "string" },
      "auto_fixable": { "type": "boolean" },
      "fix_target": {
        "type": "string",
        "enum": ["fe", "be", "db", "multiple"]
      },
      "evidence": {
        "type": "object",
        "fields": {
          "fe_reference": { "type": "string | null" },
          "be_reference": { "type": "string | null" },
          "db_reference": { "type": "string | null" }
        }
      }
    }
  },
  "summary": {
    "type": "object",
    "fields": {
      "total_findings": { "type": "integer" },
      "by_category": { "type": "object" },
      "by_severity": { "type": "object" },
      "by_layer": { "type": "object" },
      "auto_fixable_count": { "type": "integer" }
    }
  }
}
```

### fe_details.json (all modules)
- **Source:** `fe_contract` agent -> `agent_output/contracts/{module_id}/fe_details.json`
- **Required:** no (conditional — only present if FE layer exists; if absent, FE patches are skipped)
- **Shape:**
```json
{
  "type": "array",
  "description": "FE contract files that may be patched",
  "items": {
    "module_id": { "type": "string" },
    "screens": {
      "type": "array",
      "items": {
        "screen_id": { "type": "string" },
        "endpointProposals": { "type": "array" },
        "dataDisplayed": { "type": "array" },
        "dataCaptured": { "type": "array" },
        "components": { "type": "array" },
        "state_requirements": { "type": "object" },
        "navigation": { "type": "object" }
      }
    }
  }
}
```

### openapi.json (all modules)
- **Source:** `be_contract` agent -> `agent_output/contracts/{module_id}/openapi.json`
- **Required:** no (conditional — only present if BE layer exists; if absent, BE patches are skipped)
- **Shape:**
```json
{
  "type": "array",
  "description": "BE contract files that may be patched",
  "items": {
    "type": "object",
    "fields": {
      "openapi": { "type": "string" },
      "paths": {
        "type": "object",
        "description": "API paths that may be modified to fix cross-layer issues"
      },
      "components": {
        "type": "object",
        "fields": {
          "schemas": {
            "type": "object",
            "description": "Schemas that may be modified to align with FE or DB"
          },
          "securitySchemes": { "type": "object" }
        }
      }
    }
  }
}
```

### prisma_contract.json (all modules)
- **Source:** `db_contract` agent -> `agent_output/contracts/{module_id}/prisma_contract.json`
- **Required:** no (conditional — only present if DB layer exists; if absent, DB patches are skipped)
- **Shape:**
```json
{
  "type": "array",
  "description": "DB contract files that may be patched",
  "items": {
    "module_id": { "type": "string" },
    "models": {
      "type": "array",
      "items": {
        "model_name": { "type": "string" },
        "fields": { "type": "array" },
        "story_refs": { "type": "array" },
        "indexes": { "type": "array" },
        "unique_constraints": { "type": "array" },
        "enums_used": { "type": "array" }
      }
    },
    "relations": { "type": "array" },
    "enums": { "type": "array" },
    "seeds": { "type": "array" }
  }
}
```

---

## Outputs

### unified_reconcile_result.json
- **Path:** `agent_output/reviews/unified_reconcile_result.json`
- **Format:** `json`
- **Consumers:** `orchestrator` (to decide loop/proceed/escalate), `unified_review` (if looping), `normalize` (Phase 6, if proceeding)
- **Shape:**
```json
{
  "reconcile_id": {
    "type": "string",
    "description": "Unique reconcile run identifier",
    "example": "UNI-REC-2026-03-21-001"
  },
  "timestamp": {
    "type": "string",
    "format": "ISO-8601",
    "example": "2026-03-21T17:00:00Z"
  },
  "review_id_ref": {
    "type": "string",
    "description": "Reference to the unified review output this reconcile processed",
    "example": "UNI-REV-2026-03-21-001"
  },
  "cycle": {
    "type": "integer",
    "description": "Which review-reconcile cycle this is (1, 2, or 3)",
    "example": 1
  },
  "action": {
    "type": "string",
    "enum": ["loop", "proceed", "escalate"],
    "description": "What happens next. loop = re-run unified_review. proceed = contracts are consistent, move to Phase 6 Normalize. escalate = unresolvable cross-layer conflicts require human input.",
    "example": "proceed"
  },
  "changes_applied": {
    "type": "array",
    "description": "List of cross-layer changes applied to contract files",
    "items": {
      "finding_id": {
        "type": "string",
        "description": "The unified review finding this change addresses",
        "example": "UNI-F-001"
      },
      "layer": {
        "type": "string",
        "enum": ["fe", "be", "db"],
        "description": "Which contract layer was modified",
        "example": "be"
      },
      "module_id": {
        "type": "string",
        "description": "Module whose contract file was modified",
        "example": "auth"
      },
      "file": {
        "type": "string",
        "description": "Which contract file was modified",
        "enum": ["fe_details.json", "openapi.json", "prisma_contract.json"],
        "example": "openapi.json"
      },
      "change_type": {
        "type": "string",
        "enum": ["add", "modify", "remove", "rename"],
        "description": "Type of change applied",
        "example": "rename"
      },
      "path": {
        "type": "string",
        "description": "JSON path within the contract file that was changed",
        "example": "components.schemas.LoginResponse.properties.token"
      },
      "before": {
        "type": "any",
        "description": "Value before the change",
        "example": { "type": "string", "description": "Auth token" }
      },
      "after": {
        "type": "any",
        "description": "Value after the change",
        "example": { "type": "string", "description": "Access token" }
      },
      "rationale": {
        "type": "string",
        "description": "Why this change was made and how it maintains cross-layer integrity",
        "example": "Renamed 'token' to 'access_token' in BE LoginResponse to align with FE endpointProposal response_shape and industry convention"
      },
      "cascaded_to": {
        "type": "array",
        "description": "Other layers/files this change was cascaded to, if any",
        "items": {
          "layer": { "type": "string", "enum": ["fe", "be", "db"] },
          "module_id": { "type": "string" },
          "file": { "type": "string" },
          "path": { "type": "string" }
        },
        "example": []
      }
    }
  },
  "unresolved": {
    "type": "array",
    "description": "Findings that could not be auto-fixed across layers",
    "items": {
      "finding_id": {
        "type": "string",
        "example": "UNI-F-012"
      },
      "reason": {
        "type": "string",
        "description": "Why this cross-layer finding could not be resolved",
        "example": "Conflicting User model definitions in auth and dashboard modules — auth has 'role' as enum, dashboard has 'role' as string. Requires user decision on canonical definition."
      },
      "severity": {
        "type": "string",
        "enum": ["critical", "major", "minor", "info"],
        "example": "major"
      },
      "layers_affected": {
        "type": "array",
        "items": { "type": "string", "enum": ["fe", "be", "db"] },
        "example": ["be", "db"]
      }
    }
  },
  "quality_score": {
    "type": "object",
    "description": "Quality assessment across all three layers after reconciliation",
    "fields": {
      "overall": {
        "type": "number",
        "description": "Overall cross-layer quality score 0-100",
        "example": 92
      },
      "fe_be_alignment": {
        "type": "number",
        "description": "Score for FE-to-BE contract alignment 0-100",
        "example": 95
      },
      "be_db_alignment": {
        "type": "number",
        "description": "Score for BE-to-DB contract alignment 0-100",
        "example": 90
      },
      "cross_module_consistency": {
        "type": "number",
        "description": "Score for cross-module entity consistency 0-100",
        "example": 88
      },
      "naming_consistency": {
        "type": "number",
        "description": "Score for naming convention adherence 0-100",
        "example": 95
      },
      "security_completeness": {
        "type": "number",
        "description": "Score for security requirement coverage 0-100",
        "example": 93
      }
    }
  }
}
```

### Modified contract files (in-place)
- **Path:** `agent_output/contracts/{module_id}/fe_details.json`, `agent_output/contracts/{module_id}/openapi.json`, `agent_output/contracts/{module_id}/prisma_contract.json` (modified in-place as needed)
- **Format:** `json`
- **Consumers:** `normalize` (Phase 6), `unified_review` (if looping)
- **Shape:** Same as original contract files with delta patches applied

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `unified_review` | `unified_review_output.json` | Review findings drive cross-layer fixes |
| input | `fe_contract` (all modules) | `fe_details.json` | FE contract files that may be patched |
| input | `be_contract` (all modules) | `openapi.json` | BE contract files that may be patched |
| input | `db_contract` (all modules) | `prisma_contract.json` | DB contract files that may be patched |

| Blocks | Agent | Why |
|---|---|---|
| output (if looping) | `unified_review` | If action is "loop", unified_review re-runs on patched contracts |
| output (if proceeding) | `normalize` (Phase 6) | Phase 6 starts when unified reconcile passes — normalize merges the validated contracts |

---

## Orchestrator Communication

**Agent Identity:** `unified_reconcile` — Use this ID in all `node_write`, `node_read`, `tracker_read`, and `tracker_update` calls.

### Tracker Access

| Operation | Fields | Why |
|---|---|---|
| `tracker_read` | `ag` | Read agent states to confirm unified_review has completed; check loop_state for current cycle count |
| `tracker_update` | `ag`, `ao` | Report agent status and store reconcile action (loop/proceed/escalate) in output meta for orchestrator routing |

### Output Meta

Reports reconcile routing metadata:
```json
{
  "agent_id": "unified_reconcile",
  "meta": { "action": "proceed | loop | escalate", "cycle": 1 }
}
```

### Completion Signal

**Success:**
```
tracker_update({ agent_status: { agent_id: "unified_reconcile", status: "completed" }, agent_output_meta: { agent_id: "unified_reconcile", meta: { action: "proceed", cycle: 1 } } })
```

**Failure:**
```
tracker_update({ agent_status: { agent_id: "unified_reconcile", status: "failed" } })
```

### Scope Resolution

Global agent. Operates across all modules and all contract layers (FE, BE, DB) in a single invocation. Patches contract files in-place with cross-layer cascade tracking.

---

## Compressed Keymap

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

### unified_reconcile_result.json

| Key | Full Name | Description |
|---|---|---|
| `ri` | reconcile_id | Unique reconcile run identifier |
| `t` | timestamp | ISO-8601 timestamp |
| `rr` | review_id_ref | Reference to the unified review output processed |
| `cy` | cycle | Review-reconcile cycle number (1, 2, or 3) |
| `ac` | action | Next step: loop / proceed / escalate |
| `ch` | changes_applied | Array of cross-layer changes applied |
| `cfid` | finding_id (change) | Unified review finding this change addresses |
| `cl` | layer (change) | Contract layer modified: fe / be / db |
| `cm` | module_id (change) | Module whose contract was modified |
| `cfl` | file (change) | Contract file modified (fe_details.json, openapi.json, prisma_contract.json) |
| `ctp` | change_type | Type of change: add / modify / remove / rename |
| `cpt` | path (change) | JSON path within the contract file changed |
| `cbf` | before | Value before the change |
| `caf` | after | Value after the change |
| `crt` | rationale | Why this change was made and cross-layer integrity note |
| `ccs` | cascaded_to | Array of cascade entries to other layers |
| `ccl` | layer (cascade) | Cascaded-to layer |
| `ccm` | module_id (cascade) | Cascaded-to module |
| `ccf` | file (cascade) | Cascaded-to file |
| `ccp` | path (cascade) | Cascaded-to JSON path |
| `ur` | unresolved | Array of findings that could not be auto-fixed |
| `ufid` | finding_id (unresolved) | Unresolved finding ID |
| `urs` | reason | Why this cross-layer finding could not be resolved |
| `usv` | severity (unresolved) | Severity of unresolved finding |
| `ula` | layers_affected (unresolved) | Layers involved in unresolved finding |
| `qs` | quality_score | Quality assessment object across all layers |
| `qso` | overall | Overall cross-layer quality score 0-100 |
| `qfb` | fe_be_alignment | FE-to-BE contract alignment score 0-100 |
| `qbd` | be_db_alignment | BE-to-DB contract alignment score 0-100 |
| `qcm` | cross_module_consistency | Cross-module entity consistency score 0-100 |
| `qnc` | naming_consistency | Naming convention adherence score 0-100 |
| `qsc` | security_completeness | Security requirement coverage score 0-100 |

---

## Tools Required

| Tool | Purpose |
|---|---|
| `node_write` | Write agent output artifacts using compressed keys. Output key: `unified_reconcile_result` |
| `node_read` | Read input artifacts from upstream agents. Input keys: `unified_review_output`, `fe_details`, `openapi`, `prisma_contract` |
| `tracker_read` | Read tracker state — agent statuses and loop_state for cycle tracking |
| `tracker_update` | Report agent status, store reconcile action in output meta |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must maintain referential integrity when patching across layers. If a field is renamed in BE, the corresponding FE endpointProposal and DB model field must also be updated. |
| R-002 | `constraint` | `must` | Must never break existing valid cross-references. Before applying a patch, must verify it does not invalidate any existing correct relationship between layers. |
| R-003 | `constraint` | `must` | Changes to one layer must cascade appropriately to others. Every change must include cascaded_to documentation showing what other layers were affected. |
| R-004 | `constraint` | `must` | Must not exceed 3 review-reconcile cycles. If issues persist after 3 cycles, action must be "escalate". |
| R-005 | `data_handling` | `must` | Every change must be recorded in changes_applied with finding_id, layer, module_id, file, change_type, path, before, after, rationale, and cascaded_to. No silent modifications. |
| R-006 | `constraint` | `must` | After applying patches, ALL modified contract files must still conform to their respective schemas — fe_details.json, openapi.json (valid OAS 3.0), prisma_contract.json. |
| R-007 | `constraint` | `must` | Must handle partial layer sets: only patch contracts that exist. If FE layer is absent, skip FE patches entirely. If only BE+DB exist, reconcile only those two. Never fail because an absent layer's contract is missing. |
| R-007 | `not_allowed` | `must` | Must not add new endpoints, screens, or models. The reconcile agent fixes consistency issues — it does not add new functionality. |
| R-008 | `not_allowed` | `must` | Must not remove endpoints, screens, or models. If a finding suggests removal, it must go to unresolved for human decision. |
| R-009 | `constraint` | `must` | Must decide action based on remaining findings: if no critical/major findings remain, action is "proceed". If fixes were applied, action is "loop" (to verify). If non-auto-fixable critical findings remain after max cycles, action is "escalate". |
| R-010 | `interaction` | `must` | When action is "escalate", must include clear descriptions in unresolved[] with layers_affected so the user understands the cross-layer conflict and what decisions are needed. |
| R-011 | `scope_boundary` | `must` | Must only fix findings from the unified review. Must not re-examine or fix issues that belong to fe_review/fe_reconcile scope. |
| R-012 | `output_quality` | `should` | Quality scores should independently assess each cross-layer relationship (fe_be, be_db, cross_module, naming, security) rather than a single aggregate. |
| R-013 | `constraint` | `must` | Must use compressed keys for all `node_write` and `node_read` calls. Raw/uncompressed keys are rejected by the registry. |
| R-014 | `constraint` | `must` | Must use `node_write`/`node_read` for all artifact I/O. Raw file system writes are not permitted for pipeline artifacts. |
| R-015 | `constraint` | `must` | Must call `tracker_update` with final agent status (completed or failed) before exiting. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 16384 |
| max_review_cycles | 3 |
| max_changes_per_cycle | 100 |
| timeout_seconds | 600 |

---

## Scope Boundary

**In scope:**
- Processing unified review findings and determining which are auto-fixable
- Applying cross-layer delta patches to fe_details.json, openapi.json, and prisma_contract.json
- Cascading field renames, type corrections, and structural alignments across all three layers
- Recording all changes with full before/after values, rationale, and cascade documentation
- Tracking unresolved cross-layer findings with clear explanations
- Computing quality scores for cross-layer alignment, naming consistency, and security completeness
- Deciding loop/proceed/escalate based on remaining finding severity
- Updating related artifacts (screen_registry.json, navigation_graph.json, state_matrix.json, story_screen_map.json) if contract changes require it

**Out of scope:**
- Performing the review itself (that is unified_review's job)
- Within-layer FE fixes (that is fe_reconcile's job)
- Adding new screens, endpoints, or models (requires human decision or new agent run)
- Removing existing screens, endpoints, or models (requires human decision)
- Making architectural decisions about API design patterns
- Modifying user stories (that is PRD reconcile's job)
- Resolving findings that require user input on domain semantics (those go to unresolved/escalate)
- Validating the OpenAPI spec against the OAS 3.0 standard beyond basic structural integrity (that is unified_review's or openapi_validator's job)

---

## Triggers

- Orchestrator activates this agent immediately after unified_review completes
- Triggered again if previous reconcile action was "loop" and another review cycle produces new findings
- Not triggered if unified_review finds zero critical or major findings (pipeline can skip to proceed)

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | Unified review findings loaded — auto-fixable vs non-fixable categorized by layer | `log` |
| `CP-002` | All contract files loaded for affected modules | `log` |
| `CP-003` | Cross-layer patches computed with cascade analysis | `log` |
| `CP-004` | Patches applied to FE contract files | `log` |
| `CP-005` | Patches applied to BE contract files | `log` |
| `CP-006` | Patches applied to DB contract files | `log` |
| `CP-007` | All modified files validated against their schemas | `log` |
| `CP-008` | Referential integrity verified after all patches | `log` |
| `CP-009` | Quality scores computed across all layers | `log` |
| `CP-010` | Action decision made (loop/proceed/escalate) | `notify` — user informed of unified reconcile outcome and whether Phase 6 can begin |

---

## Validation Criteria

- unified_reconcile_result.json conforms to the defined schema
- Every entry in changes_applied references a valid finding_id from the unified review findings
- Every entry in changes_applied has non-null before and after values (before is null only for additions)
- cascaded_to arrays accurately reflect actual cross-layer changes made
- All finding_ids from the review that are auto_fixable: true appear in either changes_applied or unresolved (none dropped)
- Modified fe_details.json files still conform to the fe_details.json schema
- Modified openapi.json files are still valid OpenAPI 3.0 specifications
- Modified prisma_contract.json files still have valid model/relation structures
- No existing valid cross-references between layers are broken by patches
- cycle value is between 1 and 3 inclusive
- If cycle equals 3, action must be either "proceed" or "escalate" (no more loops)
- If action is "escalate", unresolved array must be non-empty with layers_affected populated
- quality_score values are between 0 and 100

---

## Context Sources

- unified_review_output.json from Unified Review Agent (findings to process)
- fe_details.json from all modules (FE contracts to patch)
- openapi.json from all modules (BE contracts to patch)
- prisma_contract.json from all modules (DB contracts to patch)
- Previous unified reconcile results (if cycle 2 or 3, to understand accumulated changes)
- Schema definitions for all three contract types (to validate patches)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | Escalates to user at max cycles — action becomes "escalate" with unresolved cross-layer findings listed for human decision |

---

## Tool Gaps

| Gap ID | Description | Needed By | Impact Without |
|---|---|---|---|
| `TG-001` | `node_write` — Universal tool for writing agent output artifacts using compressed keys with registry validation | this agent | Agent cannot persist output artifacts through the pipeline-standard interface |
| `TG-002` | `node_read` — Universal tool for reading upstream agent artifacts using compressed keys | this agent | Agent cannot load input artifacts through the pipeline-standard interface |
| `TG-003` | `tracker_read` — Universal tool for reading pipeline tracker state | this agent | Agent cannot check upstream agent completion or loop cycle state |
| `TG-004` | `tracker_update` — Universal tool for reporting agent status, completion signals, and reconcile action routing metadata | this agent | Orchestrator cannot track agent progress or determine loop/proceed/escalate routing |
| `TG-005` | Cross-layer JSON patcher that applies delta patches to fe_details.json, openapi.json, and prisma_contract.json with cascade tracking — ensuring a field rename in one layer propagates correctly to all referencing layers | this agent | Without cascade-aware patching, field renames would only fix one layer, leaving cross-layer mismatches |
| `TG-006` | OpenAPI updater that modifies OpenAPI spec files while maintaining OAS 3.0 validity — handles schema $ref updates, path modifications, and response structure changes | this agent | Direct JSON patching of OpenAPI specs could produce invalid specifications that break downstream tools |
| `TG-007` | Prisma contract updater that modifies Prisma contract definitions while maintaining model/relation validity — handles field type changes, relation updates, and index modifications | this agent | Direct JSON patching could produce invalid Prisma definitions that fail during schema generation |
| `TG-008` | Diff generator that produces human-readable cross-layer diffs showing what changed in each contract file | this agent | Users and audit trails would lack visibility into the reconcile agent's cross-layer modifications |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `unified-reconcile` |
| `agentName` | ready | `unified_reconcile` |
| `agentRole` | ready | "Cross-Layer Contract Reconciliation Agent — Three-Contract Harmony" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, escalates to user at max cycles |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | 4 inputs: unified_review_output.json (required), fe_details.json (all modules), openapi.json (all modules), prisma_contract.json (all modules) |
| `guardrails` | ready | 15 rules defined across constraint, data_handling, not_allowed, scope_boundary, output_quality, interaction categories |
| `scopeBoundary` | ready | 8 in-scope items, 8 out-of-scope items |
| `outputFormat` | ready | JSON (unified_reconcile_result.json) with full schema + in-place modified contract files across all three layers |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 10 checkpoints with actions |
| `validation` | ready | 13 validation criteria |
| `contextSources` | ready | 6 context sources |
| `metadata` | ready | phase: "5", mode: "both", granularity: "global" |
