# Architect Reconcile Agent

> **Greek:** Architektōn (Architéktōn) — "master builder"
> **Sanskrit:** वास्तुकार (Vāstukāra) — "architect"
> **Tagline:** *"The blueprint is the promise"*

---

## Agent Identity

| Field | Value |
|---|---|
| ID | `architect_reconcile` |
| Name | Architect Reconcile Agent |
| Phase | 8 — Reconciliation & Decisions |
| Type | `pipeline` |
| Granularity | `global` |
| Interaction | `autonomous` |
| Mode | `all` |
| Domain | `dev` |

---

## Goal & Objectives

**Goal:** Merge all per-module flows and all global outputs into unified module-level and system-level flow documents, then validate the complete traceability chain from user story through screen, endpoint, database model, and implementation — ensuring nothing is lost between phases.

| Priority | Objective |
|---|---|
| primary | Produce a merged module_flow.json per module and a global_flow.json that unify FE, BE, and DB flows with global architecture decisions into a single coherent blueprint |
| secondary | Validate the complete traceability chain (story -> screen -> endpoint -> DB -> impl) and flag every broken link as a gap for the Decision Pack agent |
| tertiary | Resolve all cross-module references and dependencies so that downstream agents (impl_prep, implementation) have an unambiguous dependency graph |

---

## Inputs

### fe_flow.json (per module)
- **Source:** `fe_flow` agent -> `agent_output/architecture/{module_id}/fe_flow.json`
- **Required:** no (conditional — only present if FE layer exists; if absent, module_flow.json omits frontend_flow section)
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "description": "Module identifier",
    "example": "auth"
  },
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "nodes": {
    "type": "array",
    "description": "FE flow nodes representing screens, modals, and synthetic states",
    "items": {
      "node_id": {
        "type": "string",
        "example": "FN-AUTH-001"
      },
      "type": {
        "type": "string",
        "enum": ["screen", "modal", "redirect", "error", "loading", "terminal"],
        "example": "screen"
      },
      "screen_ref": {
        "type": "string | null",
        "description": "screen_id from fe_details (null for synthetic nodes)",
        "example": "SCR-AUTH-001"
      },
      "route": {
        "type": "string | null",
        "example": "/login"
      },
      "label": {
        "type": "string",
        "example": "Login Screen"
      },
      "is_entry_point": { "type": "boolean" },
      "requires_auth": { "type": "boolean" },
      "required_roles": {
        "type": "array",
        "items": { "type": "string" }
      }
    }
  },
  "edges": {
    "type": "array",
    "description": "Transitions between FE flow nodes",
    "items": {
      "edge_id": {
        "type": "string",
        "example": "FE-AUTH-E001"
      },
      "from": { "type": "string", "description": "source node_id" },
      "to": { "type": "string", "description": "target node_id" },
      "trigger": {
        "type": "string",
        "enum": ["click", "submit", "navigate", "auto", "error", "timeout", "redirect"]
      },
      "action": {
        "type": "string",
        "enum": ["navigate", "open_modal", "close_modal", "submit_form", "fetch_data", "redirect", "show_error"]
      },
      "data_flow": {
        "carries": { "type": "array", "items": { "type": "string" } },
        "via": { "type": "string", "enum": ["route_params", "query_params", "state", "context", "props", "none"] }
      },
      "condition": { "type": "string | null" }
    }
  },
  "entry_points": {
    "type": "array",
    "items": {
      "node_id": { "type": "string" },
      "route": { "type": "string" },
      "is_default": { "type": "boolean" },
      "auth_required": { "type": "boolean" }
    }
  },
  "guards": {
    "type": "array",
    "items": {
      "guard_id": { "type": "string" },
      "type": { "type": "string", "enum": ["auth", "role", "condition", "feature_flag"] },
      "applies_to": { "type": "array", "items": { "type": "string" } },
      "config": { "type": "object" }
    }
  },
  "data_fetching": {
    "type": "array",
    "description": "Per-screen data fetching configuration (on_mount and on_action)",
    "items": { "type": "object" }
  },
  "error_states": {
    "type": "array",
    "description": "Error state nodes with recovery edges",
    "items": { "type": "object" }
  }
}
```

### be_policy_flow.json (per module)
- **Source:** `be_policy` agent -> `agent_output/architecture/{module_id}/be_policy_flow.json`
- **Required:** no (conditional — only present if BE layer exists; if absent, module_flow.json omits backend_policy section)
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "endpoints": {
    "type": "array",
    "description": "Endpoint processing chains with middleware, handlers, and error handling",
    "items": {
      "path": {
        "type": "string",
        "example": "/api/auth/login"
      },
      "method": {
        "type": "string",
        "example": "POST"
      },
      "operation_id": {
        "type": "string",
        "description": "OpenAPI operationId"
      },
      "middleware_chain": {
        "type": "array",
        "description": "Ordered middleware instances for this endpoint",
        "items": {
          "middleware_id": { "type": "string", "example": "MW-AUTH-001" },
          "type": { "type": "string", "enum": ["auth", "validation", "rate_limit", "logging", "transform", "cache", "cors", "sanitization"] },
          "name": { "type": "string", "example": "JWT Authentication" },
          "order": { "type": "number", "description": "execution order (1-based)" },
          "config": { "type": "object", "description": "middleware-specific configuration" },
          "skip_conditions": { "type": "array", "items": { "type": "string | null" } }
        }
      },
      "handler": {
        "service_function": { "type": "string", "example": "UserService.createUser" },
        "params": {
          "type": "array",
          "items": {
            "name": { "type": "string" },
            "source": { "type": "string", "enum": ["body", "params", "query", "headers", "auth_context"] },
            "field": { "type": "string" }
          }
        },
        "returns": {
          "type": { "type": "string" },
          "schema_ref": { "type": "string" }
        }
      },
      "response_transform": {
        "enabled": { "type": "boolean" },
        "operations": { "type": "array", "items": { "type": "object" } }
      },
      "error_handlers": {
        "type": "array",
        "items": {
          "status": { "type": "number" },
          "handler": { "type": "string" },
          "response_shape": { "type": "object" }
        }
      },
      "story_refs": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["US-AUTH-001"]
      }
    }
  }
}
```

### db_flow.json (per module)
- **Source:** `db_interaction` agent -> `agent_output/architecture/{module_id}/db_flow.json`
- **Required:** no (conditional — only present if DB layer exists; if absent, module_flow.json omits database_flow section)
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "operations": {
    "type": "array",
    "description": "Per-endpoint database operation mappings",
    "items": {
      "endpoint_path": {
        "type": "string",
        "example": "/api/users"
      },
      "endpoint_method": {
        "type": "string",
        "example": "POST"
      },
      "operation_id": {
        "type": "string",
        "description": "OpenAPI operationId"
      },
      "service_function": {
        "type": "string",
        "description": "service function from be_policy_flow",
        "example": "UserService.createUser"
      },
      "db_operations": {
        "type": "array",
        "description": "Prisma operations for this endpoint",
        "items": {
          "operation_id": { "type": "string", "example": "DBO-AUTH-001" },
          "model": { "type": "string", "example": "User" },
          "action": {
            "type": "string",
            "enum": ["create", "findUnique", "findMany", "update", "delete", "upsert", "aggregate", "count", "createMany", "updateMany", "deleteMany"],
            "example": "findUnique"
          },
          "fields": { "type": "object", "description": "select, data, and omit field mappings" },
          "where_clause": { "type": "object | null", "description": "filter conditions with field, operator, value_source" },
          "include_relations": { "type": "array", "items": { "type": "object" } },
          "order_by": { "type": "object | null" },
          "transaction_group": { "type": "string | null" }
        }
      },
      "read_patterns": {
        "type": "array",
        "description": "Read pattern metadata (single, list, paginated, search, aggregate)",
        "items": { "type": "object" }
      },
      "performance_flags": {
        "type": "array",
        "description": "Detected performance concerns (n_plus_1, missing_index, etc.)",
        "items": { "type": "object" }
      },
      "story_refs": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["US-AUTH-001"]
      }
    }
  },
  "transactions": {
    "type": "array",
    "description": "Multi-operation transactions with rollback strategies",
    "items": { "type": "object" }
  },
  "index_recommendations": {
    "type": "array",
    "description": "Suggested database indexes with rationale",
    "items": { "type": "object" }
  }
}
```

### normalized.json (per module)
- **Source:** `normalize` agent -> `agent_output/normalized/{module_id}/normalized.json`
- **Required:** yes
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "example": "auth"
  },
  "entities": {
    "type": "array",
    "description": "Normalized data entities with cross-contract reconciliation",
    "items": {
      "entity_name": { "type": "string", "example": "User" },
      "fe_refs": { "type": "array", "items": { "type": "string" } },
      "be_refs": { "type": "array", "items": { "type": "string" } },
      "db_refs": { "type": "array", "items": { "type": "string" } }
    }
  }
}
```

### Global Outputs (present ones from Phase 7)
- **Source:** Phase 7 global agents -> `agent_output/global/{artifact_name}.json`
- **Required:** no (conditional — only present global outputs are merged; some global agents may be skipped based on project complexity/layers. Reconcile merges whatever global outputs exist.)
- **Shape:** (summary — each references its own full schema)
```json
{
  "global_services_registry": {
    "type": "object",
    "description": "Shared services across modules (from global_services agent)"
  },
  "global_middleware_registry": {
    "type": "object",
    "description": "Middleware definitions and assignments (from global_middleware agent)"
  },
  "global_navigation": {
    "type": "object",
    "description": "Cross-module navigation graph (from global_navigation agent)"
  },
  "global_db_patterns": {
    "type": "object",
    "description": "Database naming, indexing, audit conventions (from global_db_patterns agent)"
  },
  "global_security_policies": {
    "type": "object",
    "description": "Security rules and auth requirements (from global_security agent)"
  },
  "global_integrations": {
    "type": "object",
    "description": "External integration configs (from global_integrations agent)"
  },
  "environment_config_schema": {
    "type": "object",
    "description": "Environment variable definitions (from global_env_config agent)"
  },
  "production_bootstrap": {
    "type": "object",
    "description": "Seed data, default roles, initial config (from production_bootstrap agent)"
  }
}
```

---

## Outputs

### module_flow.json (one per module)
- **Path:** `agent_output/reconciliation/{module_id}/module_flow.json`
- **Format:** `json`
- **Consumers:** `decision_pack`, `prd_generation`, `module_sequencer`, `pre_code_analysis`, `impl_prep`
- **Shape:**
```json
{
  "module_id": {
    "type": "string",
    "description": "Module this merged flow belongs to",
    "example": "auth"
  },
  "merged_at": {
    "type": "string",
    "format": "ISO-8601",
    "description": "Timestamp of merge operation"
  },
  "layers": {
    "type": "object",
    "description": "Merged flows organized by layer",
    "fields": {
      "fe": {
        "type": "object",
        "description": "Frontend flow (from fe_flow.json)",
        "fields": {
          "nodes": { "type": "array", "description": "FE flow nodes" },
          "screen_count": { "type": "number" },
          "story_refs": { "type": "array", "items": { "type": "string" } }
        }
      },
      "be": {
        "type": "object",
        "description": "Backend policy flow (from be_policy_flow.json)",
        "fields": {
          "nodes": { "type": "array", "description": "BE policy nodes" },
          "endpoint_count": { "type": "number" },
          "story_refs": { "type": "array", "items": { "type": "string" } }
        }
      },
      "db": {
        "type": "object",
        "description": "Database interaction flow (from db_flow.json)",
        "fields": {
          "nodes": { "type": "array", "description": "DB flow nodes" },
          "model_count": { "type": "number" },
          "story_refs": { "type": "array", "items": { "type": "string" } }
        }
      }
    }
  },
  "cross_layer_links": {
    "type": "array",
    "description": "Links connecting FE -> BE -> DB nodes within this module",
    "items": {
      "fe_node": { "type": "string", "example": "FE-AUTH-001" },
      "be_node": { "type": "string", "example": "BE-AUTH-001" },
      "db_node": { "type": "string", "example": "DB-AUTH-001" },
      "story_ref": { "type": "string", "example": "US-AUTH-001" },
      "chain_status": {
        "type": "string",
        "enum": ["complete", "partial", "broken"],
        "description": "Whether the full FE->BE->DB chain is intact"
      }
    }
  },
  "cross_module_dependencies": {
    "type": "array",
    "description": "References to entities/services in other modules",
    "items": {
      "target_module": { "type": "string", "example": "billing" },
      "dependency_type": {
        "type": "string",
        "enum": ["service_call", "shared_entity", "navigation", "event"],
        "example": "service_call"
      },
      "description": { "type": "string", "example": "Auth service provides getCurrentUser to billing" }
    }
  },
  "global_refs": {
    "type": "object",
    "description": "References to global registries used by this module",
    "fields": {
      "services_used": { "type": "array", "items": { "type": "string" } },
      "middleware_applied": { "type": "array", "items": { "type": "string" } },
      "security_policies_applied": { "type": "array", "items": { "type": "string" } },
      "db_patterns_applied": { "type": "array", "items": { "type": "string" } }
    }
  }
}
```

### global_flow.json
- **Path:** `agent_output/reconciliation/global_flow.json`
- **Format:** `json`
- **Consumers:** `decision_pack`, `prd_generation`, `module_sequencer`, `impl_prep`
- **Shape:**
```json
{
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "total_modules": {
    "type": "number",
    "description": "Total modules in system"
  },
  "modules": {
    "type": "array",
    "description": "Summary of each module's flow",
    "items": {
      "module_id": { "type": "string" },
      "screen_count": { "type": "number" },
      "endpoint_count": { "type": "number" },
      "model_count": { "type": "number" },
      "story_count": { "type": "number" },
      "chain_completeness": {
        "type": "number",
        "description": "Percentage of complete traceability chains (0-100)",
        "example": 95.5
      },
      "cross_module_deps": { "type": "array", "items": { "type": "string" } }
    }
  },
  "system_dependency_graph": {
    "type": "object",
    "description": "Directed graph of module-to-module dependencies",
    "fields": {
      "nodes": {
        "type": "array",
        "items": { "module_id": { "type": "string" } }
      },
      "edges": {
        "type": "array",
        "items": {
          "from": { "type": "string" },
          "to": { "type": "string" },
          "type": { "type": "string" },
          "weight": { "type": "number", "description": "Number of dependencies" }
        }
      }
    }
  },
  "global_architecture_summary": {
    "type": "object",
    "description": "Consolidated view of all global decisions",
    "fields": {
      "shared_services": { "type": "array", "items": { "type": "string" } },
      "middleware_stack": { "type": "array", "items": { "type": "string" } },
      "security_model": { "type": "string" },
      "db_conventions": { "type": "object" },
      "integration_points": { "type": "array", "items": { "type": "string" } },
      "environment_vars_count": { "type": "number" }
    }
  }
}
```

### traceability.json
- **Path:** `agent_output/reconciliation/traceability.json`
- **Format:** `json`
- **Consumers:** `decision_pack`, `prd_generation`, `module_sequencer`
- **Shape:**
```json
{
  "generated_at": {
    "type": "string",
    "format": "ISO-8601"
  },
  "chains": {
    "type": "array",
    "description": "One entry per user story, tracing through all layers",
    "items": {
      "story_id": {
        "type": "string",
        "example": "US-AUTH-001"
      },
      "module_id": {
        "type": "string",
        "example": "auth"
      },
      "screens": {
        "type": "array",
        "description": "Screens serving this story",
        "items": { "type": "string" },
        "example": ["SCR-AUTH-001"]
      },
      "endpoints": {
        "type": "array",
        "description": "API endpoints implementing this story",
        "items": { "type": "string" },
        "example": ["POST /api/auth/login"]
      },
      "db_models": {
        "type": "array",
        "description": "Database models touched by this story",
        "items": { "type": "string" },
        "example": ["User", "Session"]
      },
      "fe_flow_nodes": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["FE-AUTH-001"]
      },
      "be_flow_nodes": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["BE-AUTH-001"]
      },
      "db_flow_nodes": {
        "type": "array",
        "items": { "type": "string" },
        "example": ["DB-AUTH-001"]
      },
      "chain_status": {
        "type": "string",
        "enum": ["complete", "partial", "broken"],
        "description": "complete = all layers present, partial = some layers missing, broken = critical gap"
      },
      "gaps": {
        "type": "array",
        "description": "Missing links in the chain",
        "items": {
          "gap_type": {
            "type": "string",
            "enum": ["missing_screen", "missing_endpoint", "missing_db_model", "missing_flow_node", "orphan_endpoint", "orphan_screen"],
            "example": "missing_endpoint"
          },
          "description": {
            "type": "string",
            "example": "Story US-AUTH-001 has screen SCR-AUTH-001 but no corresponding endpoint for password reset flow"
          },
          "severity": {
            "type": "string",
            "enum": ["critical", "warning", "info"],
            "example": "critical"
          }
        }
      }
    }
  },
  "summary": {
    "type": "object",
    "description": "Aggregate traceability metrics",
    "fields": {
      "total_stories": { "type": "number" },
      "complete_chains": { "type": "number" },
      "partial_chains": { "type": "number" },
      "broken_chains": { "type": "number" },
      "total_gaps": { "type": "number" },
      "critical_gaps": { "type": "number" },
      "completeness_percentage": { "type": "number", "example": 92.3 }
    }
  }
}
```

---

## Dependencies

| Depends On | Agent | Artifact | Why |
|---|---|---|---|
| input | `fe_flow` | `fe_flow.json` (per module) | Frontend flow data to merge into module flow |
| input | `be_policy` | `be_policy_flow.json` (per module) | Backend policy flow to merge into module flow |
| input | `db_interaction` | `db_flow.json` (per module) | Database flow to merge into module flow |
| input | `normalize` | `normalized.json` (per module) | Normalized cross-contract entity data for reference resolution |
| input | `global_services` | `global_services_registry.json` | Shared services to reference in merged flows |
| input | `global_middleware` | `global_middleware_registry.json` | Middleware assignments to wire into flows |
| input | `global_navigation` | `global_navigation.json` | Cross-module navigation to validate |
| input | `global_db_patterns` | `global_db_patterns.json` | DB conventions for validation |
| input | `global_security` | `global_security_policies.json` | Security policies to validate against flows |
| input | `global_integrations` | `global_integrations.json` | External integration references |
| input | `global_env_config` | `environment_config_schema.json` | Environment variable definitions |
| input | `production_bootstrap` | `production_bootstrap.json` | Seed data and initial config |

| Blocks | Agent | Why |
|---|---|---|
| output | `decision_pack` | Decision Pack needs traceability gaps to generate questions |
| output | `prd_generation` | PRD agent needs merged flows and traceability for comprehensive document |
| output | `module_sequencer` | Sequencer needs cross-module dependency graph to determine build order |

---

## Orchestrator Communication

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

### Agent Identity

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

### Scope Resolution

Global agent — runs once across all modules. Reads `md.a` from tracker via `tracker_read` to know which modules to process for flow merging and traceability validation.

---

## Compressed Keymap

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

**module_flow.json (per module)**

| Key | Full Name | Description |
|---|---|---|
| `m` | module_id | Module identifier |
| `ma` | merged_at | Timestamp of flow merge |
| `ly` | layers | Layer breakdown object |
| `ly.fe` | fe | Frontend layer flow |
| `ly.fe.nd` | nodes | Frontend flow nodes |
| `ly.fe.sc` | screen_count | Number of screens |
| `ly.fe.sr` | story_refs | Story references for FE |
| `ly.be` | be | Backend layer flow |
| `ly.be.nd` | nodes | Backend flow nodes |
| `ly.be.ep` | endpoint_count | Number of endpoints |
| `ly.be.sr` | story_refs | Story references for BE |
| `ly.db` | db | Database layer flow |
| `ly.db.nd` | nodes | Database flow nodes |
| `ly.db.mc` | model_count | Number of models |
| `ly.db.sr` | story_refs | Story references for DB |
| `cl` | cross_layer_links | Array of cross-layer link objects |
| `cl.fn` | fe_node | Frontend node in link |
| `cl.bn` | be_node | Backend node in link |
| `cl.dn` | db_node | Database node in link |
| `cl.sr` | story_ref | Story reference for link |
| `cl.cs` | chain_status | Link chain completeness status |
| `cd` | cross_module_dependencies | Array of cross-module dependency objects |
| `cd.tm` | target_module | Target module of dependency |
| `cd.dt` | dependency_type | Type of dependency |
| `cd.ds` | description | Dependency description |
| `gr` | global_refs | Global references object |
| `gr.su` | services_used | Shared services used |
| `gr.mw` | middleware_applied | Middleware applied |
| `gr.sp` | security_policies_applied | Security policies applied |
| `gr.dp` | db_patterns_applied | Database patterns applied |

**global_flow.json**

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | Timestamp of generation |
| `tm` | total_modules | Total modules processed |
| `ms` | modules | Array of module summary objects |
| `ms.m` | module_id | Module identifier |
| `ms.sc` | screen_count | Screens in module |
| `ms.ep` | endpoint_count | Endpoints in module |
| `ms.mc` | model_count | Models in module |
| `ms.st` | story_count | Stories in module |
| `ms.cc` | chain_completeness | Chain completeness ratio |
| `ms.cd` | cross_module_deps | Cross-module dependency count |
| `dg` | system_dependency_graph | System dependency graph object |
| `dg.nd` | nodes | Graph nodes |
| `dg.ed` | edges | Graph edges |
| `gs` | global_architecture_summary | Global architecture summary object |
| `gs.ss` | shared_services | Shared services list |
| `gs.mw` | middleware_stack | Middleware stack |
| `gs.sm` | security_model | Security model description |
| `gs.dc` | db_conventions | Database conventions |
| `gs.ip` | integration_points | Integration points |
| `gs.ev` | environment_vars_count | Environment variable count |

**traceability.json**

| Key | Full Name | Description |
|---|---|---|
| `ga` | generated_at | Timestamp of generation |
| `ch` | chains | Array of traceability chain objects |
| `ch.si` | story_id | Story identifier |
| `ch.m` | module_id | Module the story belongs to |
| `ch.sr` | screens | Screens implementing the story |
| `ch.ep` | endpoints | Endpoints implementing the story |
| `ch.dm` | db_models | DB models for the story |
| `ch.fn` | fe_flow_nodes | Frontend flow nodes |
| `ch.bn` | be_flow_nodes | Backend flow nodes |
| `ch.dn` | db_flow_nodes | Database flow nodes |
| `ch.cs` | chain_status | Chain completeness status |
| `ch.gp` | gaps | Array of gap objects |
| `ch.gp.gt` | gap_type | Type of gap |
| `ch.gp.ds` | description | Gap description |
| `ch.gp.sv` | severity | Gap severity |
| `sm` | summary | Traceability summary object |
| `sm.ts` | total_stories | Total stories traced |
| `sm.cc` | complete_chains | Fully complete chains |
| `sm.pc` | partial_chains | Partially complete chains |
| `sm.bc` | broken_chains | Broken chains |
| `sm.tg` | total_gaps | Total gaps found |
| `sm.cg` | critical_gaps | Critical gaps count |
| `sm.cp` | completeness_percentage | Overall completeness percentage |

---

## Tools Required

| Tool | Purpose | Exists? |
|---|---|---|
| `node_write` | Write reconciliation output via registry-validated compressed keys. Agent calls `node_write(agent_id: "architect_reconcile", output_key: "module_flow", data: {...}, unit_id: "{module_id}")`. | Pending |
| `node_read` | Read upstream artifacts (per-module flows, normalized, global outputs). Agent calls `node_read(agent_id: "architect_reconcile", input_key: "fe_flow", unit_id: "{module_id}")`. | Pending |
| `tracker_read` | Read active modules. Agent calls `tracker_read(agent_id: "architect_reconcile", fields: ["md.a"])`. | Pending |
| `tracker_update` | Report completion/failure. Agent calls `tracker_update(agent_id: "architect_reconcile", status: "completed")`. | Pending |

---

## Guardrails

### Rules

| ID | Category | Severity | Rule |
|---|---|---|---|
| R-001 | `constraint` | `must` | Must produce a complete traceability chain for every user story. No story may lack a chain entry in traceability.json. |
| R-002 | `constraint` | `must` | Must resolve all cross-module references. If module A references module B's entity, that reference must be validated as existing. |
| R-003 | `output_quality` | `must` | Must flag every broken chain with a gap entry including gap_type, description, and severity. No silent failures. |
| R-004 | `constraint` | `must` | Every module_flow.json must contain all three layers (fe, be, db). If a layer has no nodes, it must be present but empty with an explanation. |
| R-005 | `scope_boundary` | `must` | Must not modify any input artifacts. This agent is read-only on inputs and write-only on outputs. |
| R-006 | `data_handling` | `must` | Must preserve all story_ref back-references from input flows. No story reference may be dropped during merge. |
| R-007 | `output_quality` | `should` | global_flow.json should include a system dependency graph that enables topological sorting for build order. |
| R-008 | `constraint` | `must` | Must handle partial layer sets: if only BE+DB flows exist (no FE), merge only those. module_flow.json includes a `layers_present` field. Traceability checks only validate chains for present layers. Never fail because an absent layer's flow is missing. |
| R-008 | `constraint` | `should` | Cross-layer links should connect FE -> BE -> DB nodes where the same story drives all three layers. |
| R-009 | `output_quality` | `should` | Traceability summary should compute completeness_percentage accurately as (complete_chains / total_stories * 100). |
| R-010 | `not_allowed` | `must` | Must not invent or fabricate flow nodes that do not exist in the input artifacts. Merge only; do not generate. |
| 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: "architect_reconcile", status: "completed")` before exiting on success. Must call `tracker_update(agent_id: "architect_reconcile", status: "failed", add_intervention: {...})` before exiting on failure. |
| R-014 | `constraint` | `must` | Must read active modules via `tracker_read(agent_id: "architect_reconcile", fields: ["md.a"])` when resolving scope. Must not hardcode module lists. |

### Limits

| Resource | Value |
|---|---|
| max_retries | 3 |
| max_tokens | 32768 |
| max_modules | 20 |
| timeout_seconds | 600 |

---

## Scope Boundary

**In scope:**
- Merging per-module FE, BE, and DB flows into unified module_flow.json files
- Building a system-wide global_flow.json with module dependency graph
- Validating the complete traceability chain from story to implementation
- Detecting and reporting all gaps, broken chains, and unresolved references
- Resolving cross-module dependencies (shared entities, service calls, navigation links)
- Referencing global outputs (services, middleware, security, etc.) in merged flows

**Out of scope:**
- Fixing gaps or broken chains (that is the Decision Pack agent's job to surface and the user's job to decide)
- Modifying any input artifacts
- Making architectural decisions
- Generating code or implementation artifacts
- Defining new stories, screens, or endpoints
- Running any implementation or testing

---

## Triggers

- Orchestrator activates this agent when all PRESENT per-module flows and all PRESENT global outputs are complete (absent layers/globals are not waited for)
- Requires the Phase 7 global barrier to have passed (all global agents done)
- In retrofit mode, activated only for modules flagged by the triage agent (but still produces global outputs)

---

## Checkpoints

| ID | Description | Action |
|---|---|---|
| `CP-001` | All per-module flow artifacts loaded and validated | `log` |
| `CP-002` | All global output artifacts loaded | `log` |
| `CP-003` | Per-module flow merge complete for all modules | `notify` — summary of merge results |
| `CP-004` | Cross-module dependency resolution complete | `log` |
| `CP-005` | Traceability chain validation complete | `notify` — alert if broken chains found |
| `CP-006` | global_flow.json and traceability.json written | `log` |
| `CP-007` | All output artifacts validated against schemas | `log` |

---

## Validation Criteria

- Every module in modules_registry.json has a corresponding module_flow.json
- Every module_flow.json contains all three layers (fe, be, db)
- Every user story appears in traceability.json with a chain entry
- All cross-module references resolve to existing modules and entities
- traceability.json summary counts are mathematically consistent (complete + partial + broken = total)
- global_flow.json system_dependency_graph has no orphan nodes
- No story_ref from input flows is missing in the merged output
- All gap entries have valid gap_type, description, and severity values
- Output files conform to their defined JSON schemas

---

## Context Sources

- All per-module flow artifacts (fe_flow.json, be_policy_flow.json, db_flow.json per module)
- All per-module normalized.json files
- All 8 global output artifacts from Phase 7
- modules_registry.json from Phase 1 (for module list)
- user_stories_{module_id}.json from Phase 3 (for story list reference)

---

## Operation Mode

| Field | Value |
|---|---|
| Type | `autonomous` |
| Fallback | `none` — if reconciliation fails, the pipeline cannot proceed to decisions or implementation prep |

---

## 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` | Flow merger tool that can unify FE, BE, and DB flow graphs into a single coherent module flow with cross-layer links | this agent | Manual merging is error-prone and would miss connections between layers |
| `TG-006` | Traceability chain validator that walks the full story -> screen -> endpoint -> DB -> impl chain and detects breaks | this agent | Broken chains would only be caught during implementation, causing expensive rework |
| `TG-007` | Cross-module dependency resolver that validates inter-module references (shared entities, service calls, navigation) | this agent | Unresolved cross-module references would cause integration failures during implementation |

---

## Generation Readiness

| `generate_agent` Param | Status | Notes |
|---|---|---|
| `fileName` | ready | `architect-reconcile` |
| `agentName` | ready | `architect_reconcile` |
| `agentRole` | ready | "System Flow Merger and Traceability Validator" |
| `agentDescription` | ready | Full description available from Goal section |
| `operationMode` | ready | `autonomous`, no fallback |
| `goal` | ready | 3 objectives defined with priorities |
| `inputs` | ready | Per-module flows (3 per module), normalized (per module), 8 global outputs |
| `guardrails` | ready | 14 rules defined across constraint, scope_boundary, output_quality, data_handling, not_allowed categories |
| `scopeBoundary` | ready | 6 in-scope items, 6 out-of-scope items |
| `outputFormat` | ready | JSON output with full schemas for module_flow.json, global_flow.json, traceability.json |
| `triggers` | ready | 3 triggers defined |
| `checkpoints` | ready | 7 checkpoints with actions |
| `validation` | ready | 9 validation criteria |
| `contextSources` | ready | 5 context source categories |
| `metadata` | ready | phase: "8", mode: "both", granularity: "global" |
